FlaskWeb开发-Part2-程序基本结构(第一个Flask Web程序)
first.
首先,展示一个简单的示例:Flask默认在5000端口监听,执行以下hello.py程序,可以通过浏览器访问:http://127.0.0.1:5000/
显示为hello,world
#hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello, World!</h1>'
if __name__ == '__main__':
app.run(debug=True)
浏览器显示:
其中有三点需要注意:
1.重启电脑,或者terminal之后,进入文件夹之后,要打开venv
source venv/bin/activate
2.使用书籍上:git
git checkout 2a
得到2a这个版本后,需要修改文件读写权限:
sudo chmod 777 ./hello.py
//add the following code at the tail
if __name__ == '__main__':
app.run(debug=True)
3.使用命令:
python hello.py
之后访问浏览器才可以。
接下来还有几个展示程序,其中return redirect()可以跳转到对应网址,实验中为百度。zzytest为我自己添加的函数:
from flask import Flask
from flask import make_response
from flask import redirect
from flask import abort
from flask import request
app = Flask(__name__)
@app.route('/')
def index():
#return '<h1>hello world</h1>'
#return '<h1>Bad request</h1>',400
'''# this is a make_response test
response = make_response('<h1>this document carries a cookie!</h1>')
response.set_cookie('answer','42')
return response
'''
#return redirect('http://www.baidu.com')
user_agent = request.headers.get('User-Agent')
return '<p>Your brower is %s</p>' % user_agent
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>hello,%s</h1>' % user.name
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, {}!</h1>'.format(name)
@app.route('/zzytest/')
def zzytest():
return '<h1>this is zzy test!</h1>'
if __name__ == '__main__':
app.run(debug=True)
突然发现图片违规了,其实就是一个“百度搜索”的界面。
其实,就是建立一个对应关系:将要访问的目录和对应函数映射起来
@app.route('/')
def index():
return '<h1>Hello, world</h1>'
second.
使用Flask扩展:使用Flask-Script支持命令行选项
安装:
pip install flask-script
可以选择shell, runserver运行
from flask import Flask
app = Flask(__name__)
from flask_script import Manager
manager = Manager(app)
@app.route('/')
def index():
return '<h1>hello world!</h1>'
if __name__ == '__main__':
manager.run()
可以选择网络接口:
python hello.py runserver --host 0.0.0.0
另一种可以运行hello world的代码:
from werkzeug.wrappers import Request,Response
from werkzeug.serving import run_simple
@Request.application
def hello(request):
return Response('Hello World')
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
run_simple('localhost',4000,hello)
运行示意图: