Flask中路由參數


Flask中路由參數、請求方式設置

一、參數設置

1.參數類型

Flask中參數的使用

@app.route('/parames/<username>/')
def hello_world3(username, age=20):
    return username + ''

以上代表的是路徑參數。

Flask中的參數:
1)都是關鍵字參數 
2)默認標識是<>
3)username需要和對應的視圖函數的參數名字保持一致。
4)參數允許有默認值:
如果有默認值,那么在路由中,不傳輸參數也是可以的。
如果沒有默認值,參數在路由中必修傳遞。
5)參數默認類型是string,如果想修改為其它類型,如下
<參數類型:username>

# 設置username為int類型
<int:username> 

參數語法

  • string 默認類型,會將斜線認為是參數分隔符
  • int 限制參數的類型是int類型
  • float 顯示參數對的類型是float類型
  • path 接受到的數據格式是字符串,特性會將斜線認為是一個字符

2.未指定參數類型

在url中傳入參數時,如果沒有指定參數的類型,會默認為參數是string類型。
如下:
沒有給id指定參數類型,id默認是string類型,想要對id做運算,就必須先轉化成int類型,最后返回的內容必須是字符串,所以再轉成string類型。

@house_blueprint.route('/<id>/')
def h(id):
    id = int(id) ** 5
    id = str(id)
    return id

運行結果:

 

3.指定參數類型

(1)int、float類型

給參數指定類型,就在參數前加上參數類型和冒號即可。如下,指定id是int類型,可以直接進行運算。

@house_blueprint.route('/<int:id>/')
def h(id):
    id = id ** 5
    id = str(id)
    return id
運行結果:
 

(2)path類型

指定path類型,可以獲取當前路徑,值得注意的是獲取的不是完整路徑,只是此處傳入的路徑參數,如下獲取的路徑是 testpath/test。

@house_blueprint.route('/<path:url_path>/')  #藍圖
def h(url_path):
    return 'path:%s' % url_path
 
        
運行結果:
 
@app.route('/usepath/<path:name>/', methods=['GET', 'POST'])
def use_path(name): return str(name)

userpath后面的路徑隨便寫,如

http://192.168.100.95:8080/usepath/dfdsf/dsfsdf/fdsfds/
http://192.168.100.95:8080/usepath/dfdsf/

 

(3)uuid類型

@house_blueprint.route('/<uuid:uu>') def h(uu): return 'uu:s' % uu 

(4) any:可以指定多種路徑,這個通過一個例子來進行說明:

 

@app.route('/index/<any(article,blog):url_path>/')
def item(url_path):
return url_path

以上例子中,item這個函數可以接受兩個URL,一個是http://127.0.0.1:5000/index/article/,另一個是http://127.0.0.1:5000/index//blog/。並且,一定要傳url_path參數,當然這個url_path的名稱可以隨便。

請求方法
常用的有5中,請求方式默認是GET,可以在路由中設置,如下

methods=['GET', 'POST','DELETE'.'PUT','HEAD']

二、請求方式設置

flask中請求默認是get請求,若想要指定其他請求方式,用參數methods指定。如用戶注冊時,需要把用戶填寫的數據存入數據庫,生成一條新用戶的記錄,此處就需要用到post請求。

@house_blueprint.route('/register/', methods=['POST']) def register(): register_dict = request.form username = register_dict['usrename'] password = register_dict.get('password') user = User() user.username = username user.password = password db.session.add(user) db.session.commit() return '創建用戶成功'
https://www.jianshu.com/p/e1b7d85efccb


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM