flask-one
阿新 • • 發佈:2017-06-29
border ans wid return neu san 好處 pat html
安裝:
1 pip install Flask
啟動第一個腳本:
python hello.py
訪問地址:http://127.0.0.1:5000
腳本如下:
1 from flask import Flask 2 app = Flask(__name__) 3 4 @app.route(‘/‘) #路由指定 5 def hello_world(): 6 return ‘Hello worlds summerkxy‘ 7 if __name__ == ‘__main__‘: #只有在本例使用的時候才會啟動應用,包含該文件的話,不啟動應用 8 app.debug = True #開啟調試模式 9 app.run()
其中 app.debug = True 開啟調試模式,也可以用app.run(debug=True)中加入參數;好處:在修改程序後不用重新啟動應用。 這是最簡單的應用。
1 from flask import Flask 2 app = Flask(__name__) 3 4 #第一個路由 5 @app.route(‘/‘) 6 def hello_world(): 7 return ‘Hello worlds summerkxy‘ 8 9 #第二個路由 10 @app.route(‘/summerkxy‘) 11def summer(): #函數名隨意,不可與自帶函數名沖突; 12 return "Hello summerkxy" 13 if __name__ == ‘__main__‘: 14 app.debug = True 15 app.run()
帶有參數的url
1 @app.route(‘/show/<username>‘) 2 def show_user(username): 3 return "show %s" % username
多參數傳遞:
1 @app.route(‘/show/<username>/<age>參數帶有類型:‘) 2 def show_user(username,age): 3 return "show "+username+" age:"+age
@app.route("/age/<int:age>") def show_age(age): return "show age %d" % age
轉換器有三種:
int | float | path |
整型 | 可整型也可浮點型 | 普通類型,可帶斜線 |
url唯一性對比:
1 @app.route("/about/") 2 def show_about(): 3 return "about/" 4 5 @app.route("/about") 6 def show_about1(): 7 return "about"事實上只會匹配到第一個url 構造url url_for() #未知 根據請求的的方式,調用不同的函數,從而返回不同內容:
1 from flask import Flask,url_for #url_for暫時沒用到 2 from flask import request 3 app = Flask(__name__) 4 5 @app.route("/") 6 def index(): 7 return "index" 8 9 @app.route(‘/login‘,methods=[‘GET‘,‘POST‘]) #首先會根據methods列表中的元素判斷,如果沒有找到就報錯405方法不允許; 10 def login(): 11 if request.method == ‘POST‘: 12 return do_the_login() 13 else: 14 return show_the_login_form() 15 def do_the_login(): 16 return "post" 17 def show_the_login_form(): 18 return "else method" 19 20 if __name__ == ‘__main__‘: 21 app.debug = True 22 app.run()
引入靜態css,js文件
1 @app.route("/hello") 2 def hello(): 3 cssurl = url_for(‘static‘, filename=‘style.css‘) 4 return render_template("hello.html",age=cssurl) 5 .html文件中 6 <link type="text/css" rel="stylesheet" href="{{ age }}"> 7 <h1>{{ age }}</h1>問題:單獨一個url返回一個樣式,毫無意義,如何傳遞多個值 使用list/dist即可 向模版文件中傳遞參數:
1 @app.route("/hello") 2 def hello(name=‘summerkxy‘): 3 return render_template("hello.html",age=name)#變量名age就是傳遞到模版文件中的 4 .html文件 5 <h1>hello {{ name }}</h1>
flask-one