Python web框架 flask 筆記 (1)
import datetime
from flask import Flask,redirect,url_for
from werkzeug.routing import BaseConverter
from flask import request,jsonify,render_template
from flask import make_response,session
import json
app=Flask(__name__)
#session需要使用到的祕鑰字串
app.config['SECRET_KEY']='3424sedfrer34rwerrwef'
def fl():
return 'ok3'
#app.add_url_rule(rule=訪問的url,endpoint=路由別名,view_func=檢視名稱,methods=[允許訪問的方法])
app.add_url_rule(rule='/kj',endpoint='name2',view_func=fl,methods=['GET'])
#設定cookie和headers
@app.route('/set_cookie')
def set_cookie():
response=make_response('
cookie
')
#cookie有效時長30天也可以是hour second minute
time=datetime.datetime()+datetime.timedelta(days=30)
response.set_cookie('user','admin',expires=time)
response.set_cookie('pass','123456',expires=time)
response.headers['X-Something']='A value'
response.headers['Server']='My special http server'
return response
#獲取cookie
@app.route('/get_cookie')
def get_cookie():
name="使用者名稱:"+request.cookies.get('user')+"密碼:"+request.cookies.get('pass')
return name
#刪除cookie
@app.route('/del_cookie')
def del_cookie():
response=make_response('delete cookie')
#1.使用Response的set_cookie進行清除
response.set_cookie('user','',expires=0)
response.set_cookie('pass','',expires=0)
#2.使用Response的 delete_cookie方法.
#response=make_response('delete cookie')
#response.delete_cookie('user')
#response.delete_cookie('pass')
#return response
return response
#設定session
@app.route('/session1')
def session1():
session['user']='hw'
session['pass']='zj'
return 'login success'
#獲取session
@app.route('/session2')
def session2():
us=session.get("user")
pa=session.get("pass")
return 'hello %s %s'%(us,pa)
#返回json資料
#1
@app.route('/json1')
def json1():
data={'name':'HW','first':'ZJ'}
return jsonify(data)
#2
@app.route('/json2')
def json2():
return jsonify(hour=12,second=21)
#“””?自定義轉換器?
class RegexConverter(BaseConverter):
# 重寫?父類的屬性,定義轉換器?規則
def __init__(self,url_map):
super(RegexConverter,self).__init__(url_map)
#實現驗證手機號碼的正則”””
self.regex='1[34578][\d]{9}'
#定義檢視函式下的返回值
def to_python(self,value):
val=value
return val
def to_url(self,value):
return value
# 將?自定義的轉換器?新增到轉換器?列列表中
app.url_map.converters['re']=RegexConverter
@app.route('/new/<re:mobile_id>')
def mobile(mobile_id):
return 'mobile is:%s' % mobile_id
#自動轉到new下指定的手機號碼
@app.route('/index')
def index():
url=url_for('mobile',mobile_id='13434235453')
return redirect(url)
#跳轉到其他地址
@app.route('/kj/')
def er(url):
print(url)
return 'ok1'
#endpoint=路由別名
@app.route('/',endpoint='name1')
def first_flask(url):
print(url_for('name1',url=url)) #如果設定了url引數,url_for(別名,加引數)
return 'ok2'
#request
@app.route('/request',methods=['GET','POST'])
def post():
name=request.form.get('name')
age=request.form.get('age')
score=request.form.get('score')
city=request.args.get('city')
qw=json.dumps(request.cookies)
return 'hello name=%s age=%s score=%s city=%s qw=%s'%(name,age,score,city,qw)
#上傳檔案
@app.route('/upload',methods=['GET','POST'])
def upload():
if request.method=='GET':
return render_template('upload.html')
else:
f=request.files.get('file')
if not f:
return '未上傳'
#f.save(os.path.join('app/static',filename))
else:
f.save( f.filename)
return '上傳成功'
if __name__=='__main__':
app('127.0.0.1','5000')
upload.html
請選擇一個檔案上傳