0

这是代码:

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
4

1 回答 1

3

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

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

在我看来,AppServer 类似乎只是在应用程序启动时设置一些配置。因此,您必须在 if 语句之外执行此操作。

于 2013-09-25T12:44:03.973 回答