【flask】python上启动web服务

如下实验基于Ubuntu==18.0四、anaconda==2019.0七、python==3.六、flask==1.1.1python


启动web服务

导入flask中的Flask模块后使用Flask初始化web服务对象app = Flask(__name__)git

这个app就是web服务的对象,接下来只要调用app.run()方法就能够启动web服务器了,就是这么简单github

启动log以下web

/home/yukiti2007/anaconda3/envs/tf2/bin/python /home/yukiti2007/IdeaProjects/sample/python/flask/router.py
 * Serving Flask app "router" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

能够看出flask默认是在5000端口启动web服务的flask

从log中的警告能够看出,这种启动方式只是在开发阶段使用,不推荐在生产环境中使用服务器

若是是生产环境,建议使用WSGI server启动服务app


app.run()方法有5个参数函数

参数名 意义 默认值
host 监听的主机ip地址 127.0.0.1(localhost)
port web服务启动端口 5000
debug 是否以debug模式启动 None
load_dotenv 是否加载环境变量,默认会加载以.env.flaskenv结尾的文件 True
options 其余选项(由于flask底层是经过Werkzeug实现的,因此这些选项会传递给Werkzeug,详细信息须要查看werkzeug.serving.run_simple方法) -

若是不想使用5000端口启动服务,只须要加上参数prot=8080就能够以8080端口启动服务了ui

另外,因为默认的监听ip地址是127.0.0.1,因此启动的服务只能本机访问url

若是须要在其余机器上也能访问,须要将监听端口设为0.0.0.0

下面以如下参数启动服务app.run(host="0.0.0.0",port=8080,debug=True),启动log以下

/home/yukiti2007/anaconda3/envs/tf2/bin/python /home/yukiti2007/IdeaProjects/sample/python/flask/router.py
 * Serving Flask app "router" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 249-050-533

添加路由

flask添加路由有2种方式

  1. 使用装饰器route()
  2. 使用函数add_url_rule()

下面咱们使用两种方式添加两个路由试试

# 在方法上添加装饰器
@app.route("/hello1")
def hello_world1():
    return "hello_world1"

# 使用函数添加
def hello_world2():
    return "hello world2"
app.add_url_rule("/hello2", view_func=hello_world2)

访问成功,同时也自动打印了访问log

192.168.140.1 - - [08/Aug/2019 16:23:30] "GET /hello2 HTTP/1.1" 200 -
192.168.140.1 - - [08/Aug/2019 16:23:39] "GET /hello1 HTTP/1.1" 200 -


可是这样添加的路由只支持GET方式的请求,经过POST方式访问的话会拒绝响应

192.168.140.1 - - [08/Aug/2019 16:33:26] "POST /hello1 HTTP/1.1" 405 -
192.168.140.1 - - [08/Aug/2019 16:33:44] "POST /hello2 HTTP/1.1" 405 -

能够经过添加method的方式来制定响应请求的Method

# 装饰器方式
@app.route("/hello1", methods=["GET", "POST"])

# 使用函数方式
app.add_url_rule("/hello2", view_func=hello_world2, methods=["GET", "POST"])

重启服务之后再次以POST方式尝试访问,响应成功

192.168.140.1 - - [08/Aug/2019 16:40:29] "POST /hello1 HTTP/1.1" 200 -
192.168.140.1 - - [08/Aug/2019 16:40:50] "POST /hello2 HTTP/1.1" 200 -

完整代码已经上传到github

相关文章
相关标签/搜索