import flask
app = flask.Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
# @app.route('/hello/<name>')
def hello(name=None):
# 使用 render_template() 方法可以渲染模板
# Flask 会在 templates 文件夹内寻找模板
return type(flask.render_template('hello.html'))
# string (缺省值) 接受任何不包含斜杠的文本
# int 接受正整数
# float 接受正浮点数
# path 类似 string ,但可以包含斜杠
# uuid 接受 UUID 字符串
@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
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % flask.escape(subpath)
# 告诉 Flask 正在处理一个请求
with app.test_request_context():
# 模仿访问时的传参域名
# url_for 用于构建指定函数的 URL
print(flask.url_for('index'))
print(flask.url_for('hello'))
print(flask.url_for('hello', next='/'))
print(flask.url_for('show_user_profile', username='John Doe'))
@app.route('/login', methods=['GET', 'POST'])
def login():
# 检测访问请求方法
if flask.request.method == 'POST':
# 通过使用 method 属性可以操作当前请求方法,通过使用 form 属性处理表单数据
# return flask.request.form['username']
return flask.request.args.get('username')
else:
return index()
# 处理错误信息
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
# http://192.xxx.xxx.xxx
app.run(host='0.0.0.0', port=80, debug=True)
获取本地网页内容
import requests
res = requests.get('http://127.0.0.1:3372')
print(res.status_code)
print(res.text)
res = requests.get('http://127.0.0.1:3372/hello')
print(res.status_code)
print(res.text)
res = requests.get('http://127.0.0.1:3372/user/hjhcos')
print(res.status_code)
print(res.text)
res = requests.get('http://127.0.0.1:3372/post/123456')
print(res.status_code)
print(res.text)
res = requests.get('http://127.0.0.1:3372/path/sdfsafd.txt')
print(res.status_code)
print(res.text)