from flask import Flask app = Flask(__name__) //@后面跟function是装饰器的左右
//route()里面填写的是页面,里也可以写(‘/user/about’)这里就是指的用户相关页面,这里指的是主页面 @app.route('/') def hello_world(): return 'Hello World!'
//返回一个value给用户,在端口运行后,用户可以看到 if __name__ == '__main__': app.run()
打开127.0.0.1:5000就能看到
这里接单介绍一下route的左右,它是在用户请求URL之后,例如‘/’,function返回一个值给用户,这里return可以是html,例如:
@app.route('/') def hello_world(): return 'Hello World!' @app.route('/another') def another(): return '<h2>this another page</h2>'
当你在端口输入http://127.0.0.1:5000/another
会弹出如下画面:
这只是一个简单的返回html,实际上你可以返回一个html template,这样做更好。
#如果你想在你的url中使用变量,你可以这样做 @app.route('/profile/<username>') def profile(username): return 'Hey there %s' % username
则在端口输入http://127.0.0.1:5000/profile/gary
会看到如下:
Hey there gary
接下来来讲述一下falsk里面的http方法:
@app.route('/') def index(): return 'Method used: %s' % request.method #我们检查你访问页面使用的方法 if __name__ == '__main__': app.run()
效果如下所示:
#由于默认访问方式为get,因此我们添加post方法 @app.route('/bacon',methods=['GET', 'POST']) def bacon(): if request.method == 'POST': return "You are using post" else : return "You are probably using get"
#这样你在使用不同方式访问的时候,会显示不同的语句。
接下来我们简单讲述一下怎么使用模版: