I'm getting syntaxt error on an "if" statement, while running my Flask application on pythoneverywhere.com

StackOverflow https://stackoverflow.com/questions/19003777

  •  29-06-2022
  •  | 
  •  

문제

Here's the code:

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()

I get the following error when trying to run it on https://www.pythonanywhere.com/ And I'm losing my mind.

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
도움이 되었습니까?

해결책

Python is telling you that you can't apply a decorator to an if statement. Decorators are for callables (functions, classes etc.)

Also PythonAnywhere uses WSGI for web apps, so your if statement will never be entered.

It also seems to me like the AppServer class is only there to set up some config when the app is started. So you'd have to do that outside of the if statement.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top