用桌面程序数据馈送 django Web 服务器



我正在尝试将一些数据库信息从桌面ERP发送到充当Web界面的django Web服务器。我尝试的第一件事是使用请求模块来"伪造"带有附加文件的 POST。然而,这是一种明显肮脏(但有效)的方法。我通过会话使用身份验证。有没有一种干净(更)的方法可以做到这一点?

我的代码:

headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Encoding': 'gzip, deflate',
           'Accept-Language': 'en-US,en;q=0.5',
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0',
           'Referer': 'https://auth.afip.gov.ar/contribuyente/',
           'Connection': 'keep-alive',
           }

session = requests.Session()
response = session.get('http://192.168.0.101:8000/sincronizacion/', headers=headers)
soup = BeautifulSoup(response.text)
csrf_value = soup.find(attrs={'name': 'csrfmiddlewaretoken', })['value']
login_info = {'username': 'user', 'password': 'pass', 'csrfmiddlewaretoken': csrf_value,
              'next': '/sincronizacion/', }
response = session.post('http://192.168.0.101:8000/login/?next=/sincronizacion/', data=login_info, headers=headers)
soup = BeautifulSoup(response.text)
csrf_value = soup.find(attrs={'name': 'csrfmiddlewaretoken', })['value']
datos_odontologos = {'test': 'test', 'csrfmiddlewaretoken': csrf_value} # test represents a future csv attachment
response = session.post('http://192.168.0.101:8000/sincronizacion/', data=datos_odontologos)
print(response.status_code)

最好的方法是使用 django 发送的 csrf cookie,并在发布一些数据时通过 http 标头将其发回:

>>> session = requests.Session()
>>> # get the cookie
>>> resp = session.get(url)
>>> # post data with csrf header using the cookie value
>>> resp = session.post(url, data=data, headers={"X-CSRFToken": resp.cookies['csrftoken'])

这样,您就不必解析 html 结果来获取 csrf 令牌或修改发送的数据。

最新更新