如何使用python3从http post请求中解析/提取表单字段?

2024-04-25 21:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析来自HTTP Post请求主体的表单数据

HTTP post正文如下所示

------WebKitFormBoundary9L2CBBUR67tDDqbZ Content-Disposition: form-data; name="newRestaurantName"

papa jones ------WebKitFormBoundary9L2CBBUR67tDDqbZ--

我的表单是使用此代码创建的

<html><body><h1>Make a New Restaurant</h1><form method = 'POST' enctype='multipart/form-data' action = '/restaurants/new'><input name = 'newRestaurantName' type = 'text' placeholder = 'New Restaurant Name' > <input type='submit' value='Create'></form></body></html>

这是我的HTTP post请求处理程序

def do_POST(self):
    try:
        if self.path.endswith("/restaurants/new"):
            content_length = int(self.headers['Content-Length'])
            body = self.rfile.read(content_length).decode('utf-8')
            print(body)
            # TODO get restuarant name from body
            restuarantName = ""
            newRestaurant = Restaurant(name=restuarantName)
            session.add(newRestaurant)
            session.commit()
            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.send_header('Location', '/restaurants')
            self.end_headers()


    except:
        pass

我无法解析HTTP主体以便提取餐厅名称。我尝试使用json.load()和cgi.parse_multipart(self.rfile,pdict)

我怎样才能正确地做到这一点


Tags: nameselfformsendhttp表单htmltype