用Python来创建Flask

安装SQLAlchemy

pip3 install flask-sqlalchemy

检查SQLAlchemy version

pip3 show sqlalchemy

from flask import Flask

# sets the name of your app to the name of your module ("app" if "app.py" is the name of your file)
app = Flask(__name__)

# @app.route is a Python decorator. 
# Decorators take functions and returns another function, usually extending the input function with additional ("decorated") functionally.
# @app.route is a decorator that takes an input function index() as the callback that gets invoked when a request to route / comes in from a client.
@app.route('/')
def index():
    return 'Hello World!'

写好了上面的python代码,就得运行
Running the flask app
To start the server

  • We run a flask app defined at app.py with FLASK_APP=app.py flask run
    • FLASK_APP must be set to the server file path with an equal sign in between. No spaces. FLASK_APP = app.py will not work.
  • To enable live reload, set export FLASK_ENV=development in your terminal session to enable debug mode, prior to running flask run. Or call it together with flask run:
$ FLASK_APP=app.py FLASK_DEBUG=true flask run

Alternative approach to run a flask app: using
Instead of using $ flask run, we could have also defined a method

if __name__ == '__main__':
	app.run()

at the bottom of the app.py script, and then called $ python3 app.py in our terminal to invoke app.run() and run the flask app this way.


Externally Visible Server
The default setting to run the development server, ie. app.run(), makes the Flask app is accessible only from your own local computer. You will get a connection error if you try to access the app from another computer, even on the same network.

To enable access to a trustworthy user within the network, you can add –host=0.0.0.0 in the command line:

$ flask run --host=0.0.0.0

Or, you can define the host inside the python main function:

if __name__ == '__main__':
	app.run(host="0.0.0.0")

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121221186