基於hi-nginx的web開發(python篇)——表單處理和檔案上傳,

來源:互聯網
上載者:User

基於hi-nginx的web開發(python篇)——表單處理和檔案上傳,

hi-nginx會自動處理表單,所以,在hi.py架構裡,要做的就是直接使用這些資料。

表單資料一般用GET和POST方法提交。hi-nginx會把這些資料解析出來,放在form成員變數裡。對python來說,要做的就是使用has_form和get_form方法取出想要的資料。

例如路由如下:

@app.route('^/form/?$',['GET','POST'])def form(req,res,param):    name='None'    if req.has_form('name'):        name=req.get_form('name')    res.content('{}={}'.format('name',name))    res.status(200)

上面的路由表示可以使用get和post兩種方法向/form提交名為name的資料。可以用curl測試下:

curl -i http://localhost:8080/form?name=123

或者

curl -i -d 'name=123'  http://localhost:8080/form

hi.py處理表單的方式就是這麼直接簡單。

以上路由還可以直接處理檔案上傳,只需把name理解為上傳檔案的臨時地址就可以了:

echo 'test upload file' > name.file

curl -i  -F'name=@name.file' http://localhost:8080/form

 

表示當我們把檔案name.file上傳給/form時,該檔案會被暫時儲存在hi-nginx安裝目錄下的temp目錄中,檔案名稱為temp/94ffcfe29b03c0c7368a2fdd842d54ca.file。因此,我們要做的僅僅是把該檔案移動到想要的地址去就行了。

因為檔案有大小,伺服器也會對檔案大小做出限制,所以最好是使用nginx的client_max_body_size,比如

client_max_body_size 100k;

命令限制檔案上傳的大小限制。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.