用Python来创建Flask

本文介绍了如何安装和使用SQLAlchemy,以及如何通过Flask框架创建一个简单的Web应用。首先,通过pip3 install flask-sqlalchemy安装所需库。接着,设置Flask应用并定义路由。在终端中,使用FLASK_APP和FLASK_DEBUG环境变量启动带有热重载功能的开发服务器。若要使应用在局域网内可访问,需指定host为0.0.0.0。
摘要由CSDN通过智能技术生成

安装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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值