python 通过flask搭建web服务

一、安装依赖

pip install Flask

 

二、简单的应用


from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
return 'Hello World!'


if __name__ == '__main__':
app.run(host='0.0.0.0', port=9011)

python app.py 后,即可在web中输入ip和端口进行访问

 

三、打开调试模式

如果启用了调试支持,在代码修改的时候服务器能够自动加载, 并且如果发生错误,它会提供一个有用的调试器

app.debug = True 在run方法前设置标志位.
或者作为 run 的一个参数传入

app.run(debug=True)

 

四、路由

route()装饰器是用于把一个函数绑定到一个 URL 上。

例如:
@app.route('/hello')
def hello():
return 'Hello World

但是不仅如此!你可以动态地构造 URL 的特定部分,也可以在一个函数上附加多个规则。

变量规则:

为了给 URL 增加变量的部分,你需要把一些特定的字段标记成 <variable_name>。这些特定的字段将作为参数传入到你的函数中。当然也可以指定一个可选的转换器通过规则 <converter:variable_name>
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

 

五、打包到docker的Dockerfile


# base image
#FROM centos
FROM python:2.7
# MAINTAINER
MAINTAINER guomei@360.cn
ADD requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY ./app.py /app/
WORKDIR /app
EXPOSE 9022
CMD ["python","/app/app.py"]

 

You May Also Like

About the Author: daidai5771

发表评论

电子邮件地址不会被公开。 必填项已用*标注