我在pythoneverywhere.com上运行我的Flask应用程序时,在“if”语句中遇到syntaxt错误

时间:2013-09-25 11:33:42

标签: python-2.7 pythonanywhere

以下是代码:

import datetime

from flask import Flask, request, abort, Blueprint

import settings

app = Flask(__name__)

class AppServer:
    """Initialise the web app"""

    def __init__(self):
        """Dynamically create and register uri handlers from the list of 
        modules specified in settings.py"""
        handlers = []

        # register url handlers
        for mod in settings.MODULES:
            self.register_module(mod)


    def register_module(self, module):
        """Dynamically load and register module from ./modules"""
        try:

            name = "modules." + module

            # import the module
            mod = __import__(name)
            components = name.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)

            mod = getattr(mod, settings.MODULES[module]['class'])

            # create and register the blueprint
            blueprint = Blueprint(module, name + "." + settings.MODULES[module]['class'],
                                    template_folder="modules/" + module + "/templates")

            blueprint.add_url_rule(settings.MODULES[module]["uri"], view_func=mod.as_view(module), methods=mod.methods)
            app.register_blueprint(blueprint)

        except Exception as e:
            print ("Failed to load class " + settings.MODULES[module]['class'] + " for module " + module)
            raise


@app.context_processor
def inject_year():
    return dict(year=datetime.datetime.now().year)

@app.route("/")
if __name__ == "__main__":
    server = AppServer()
    app.run()

尝试在https://www.pythonanywhere.com/上运行时出现以下错误 我正在失去理智。

2013-09-25 11:22:58,675 :  File "/home/username/mysite/app.py", line 65
2013-09-25 11:22:58,675 :    if __name__ == "__main__":
2013-09-25 11:22:58,675 :     ^
2013-09-25 11:22:58,675 :SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:3)

Python告诉您不能将装饰器应用于if语句。装饰器用于可调用(函数,类等)。

此外,PythonAnywhere将WSGI用于Web应用程序,因此永远不会输入您的if语句。

在我看来,AppServer类只是在启动应用程序时设置一些配置。所以你必须在if语句之外做到这一点。