标签归档:http-headers

如何在Python 2中发送HEAD HTTP请求?

问题:如何在Python 2中发送HEAD HTTP请求?

我在这里尝试做的是获取给定URL的标头,以便确定MIME类型。我希望能够查看是否http://somedomain/foo/将返回例如HTML文档或JPEG图像。因此,我需要弄清楚如何发送HEAD请求,以便无需下载内容就可以读取MIME类型。有人知道这样做的简单方法吗?

What I’m trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?


回答 0

编辑:此答案有效,但是现在您应该使用下面其他答案中提到的请求库。


使用httplib

>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]

还有一个getheader(name)获取特定的标头。

edit: This answer works, but nowadays you should just use the requests library as mentioned by other answers below.


Use httplib.

>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]

There’s also a getheader(name) to get a specific header.


回答 1

urllib2可用于执行HEAD请求。这比使用httplib更好,因为urllib2为您解析URL,而不是要求您将URL分为主机名和路径。

>>> import urllib2
>>> class HeadRequest(urllib2.Request):
...     def get_method(self):
...         return "HEAD"
... 
>>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))

头可以通过response.info()像以前一样使用。有趣的是,您可以找到重定向到的URL:

>>> print response.geturl()
http://www.google.com.au/index.html

urllib2 can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path.

>>> import urllib2
>>> class HeadRequest(urllib2.Request):
...     def get_method(self):
...         return "HEAD"
... 
>>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))

Headers are available via response.info() as before. Interestingly, you can find the URL that you were redirected to:

>>> print response.geturl()
http://www.google.com.au/index.html

回答 2

强制Requests方式:

import requests

resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

Obligatory Requests way:

import requests

resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

回答 3

我认为也应该提及Requests库。

I believe the Requests library should be mentioned as well.


回答 4

只是:

import urllib2
request = urllib2.Request('http://localhost:8080')
request.get_method = lambda : 'HEAD'

response = urllib2.urlopen(request)
response.info().gettype()

编辑:我刚开始意识到有httplib2:D

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert resp[0]['status'] == 200
assert resp[0]['content-type'] == 'text/html'
...

连结文字

Just:

import urllib2
request = urllib2.Request('http://localhost:8080')
request.get_method = lambda : 'HEAD'

response = urllib2.urlopen(request)
response.info().gettype()

Edit: I’ve just came to realize there is httplib2 :D

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert resp[0]['status'] == 200
assert resp[0]['content-type'] == 'text/html'
...

link text


回答 5

为了完整起见,有一个与使用httplib接受的答案等效的Python3答案。

基本相同的代码只是该库不再被称为httplib而是http.client

from http.client import HTTPConnection

conn = HTTPConnection('www.google.com')
conn.request('HEAD', '/index.html')
res = conn.getresponse()

print(res.status, res.reason)

For completeness to have a Python3 answer equivalent to the accepted answer using httplib.

It is basically the same code just that the library isn’t called httplib anymore but http.client

from http.client import HTTPConnection

conn = HTTPConnection('www.google.com')
conn.request('HEAD', '/index.html')
res = conn.getresponse()

print(res.status, res.reason)

回答 6

import httplib
import urlparse

def unshorten_url(url):
    parsed = urlparse.urlparse(url)
    h = httplib.HTTPConnection(parsed.netloc)
    h.request('HEAD', parsed.path)
    response = h.getresponse()
    if response.status/100 == 3 and response.getheader('Location'):
        return response.getheader('Location')
    else:
        return url
import httplib
import urlparse

def unshorten_url(url):
    parsed = urlparse.urlparse(url)
    h = httplib.HTTPConnection(parsed.netloc)
    h.request('HEAD', parsed.path)
    response = h.getresponse()
    if response.status/100 == 3 and response.getheader('Location'):
        return response.getheader('Location')
    else:
        return url

回答 7

顺便说一句,当使用httplib时(至少在2.5.2上),尝试读取HEAD请求的响应将阻塞(在读取行中),随后失败。如果您未在响应中发出已读消息,则无法在连接上发送另一个请求,则需要打开一个新请求。或者接受两次请求之间的长时间延迟。

As an aside, when using the httplib (at least on 2.5.2), trying to read the response of a HEAD request will block (on readline) and subsequently fail. If you do not issue read on the response, you are unable to send another request on the connection, you will need to open a new one. Or accept a long delay between requests.


回答 8

我发现httplib比urllib2快一点。我为两个程序计时-一个使用httplib,另一个使用urllib2-将HEAD请求发送到10,000个URL。httplib的速度快了几分钟。 httplib的总统计为:实际6m21.334s用户0m2.124s sys 0m16.372s

的urllib2的总的统计是:实9m1.380s用户0m16.666s SYS 0m28.565s

有人对此有意见吗?

I have found that httplib is slightly faster than urllib2. I timed two programs – one using httplib and the other using urllib2 – sending HEAD requests to 10,000 URL’s. The httplib one was faster by several minutes. httplib‘s total stats were: real 6m21.334s user 0m2.124s sys 0m16.372s

And urllib2‘s total stats were: real 9m1.380s user 0m16.666s sys 0m28.565s

Does anybody else have input on this?


回答 9

还有另一种方法(类似于Pawel的答案):

import urllib2
import types

request = urllib2.Request('http://localhost:8080')
request.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)

只是为了避免在实例级别使用无限制的方法。

And yet another approach (similar to Pawel answer):

import urllib2
import types

request = urllib2.Request('http://localhost:8080')
request.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)

Just to avoid having unbounded methods at instance level.


回答 10

可能更容易:使用urllib或urllib2。

>>> import urllib
>>> f = urllib.urlopen('http://google.com')
>>> f.info().gettype()
'text/html'

f.info()是类似字典的对象,因此您可以执行f.info()[‘content-type’]等。

http://docs.python.org/library/urllib.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/httplib.html

文档指出,通常不直接使用httplib。

Probably easier: use urllib or urllib2.

>>> import urllib
>>> f = urllib.urlopen('http://google.com')
>>> f.info().gettype()
'text/html'

f.info() is a dictionary-like object, so you can do f.info()[‘content-type’], etc.

http://docs.python.org/library/urllib.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/httplib.html

The docs note that httplib is not normally used directly.


将标头添加到python请求模块

问题:将标头添加到python请求模块

之前我使用httplib模块在请求中添加标头。现在,我正在对该requests模块尝试相同的操作。

这是我正在使用的python请求模块:http : //pypi.python.org/pypi/requests

如何向标头添加标题,request.postrequest.get说必须foobar在标头的每个请求中添加密钥。

Earlier I used httplib module to add a header in the request. Now I am trying the same thing with the requests module.

This is the python request module I am using: http://pypi.python.org/pypi/requests

How can I add a header to request.post() and request.get(). Say I have to add foobar key in each request in the header.


回答 0

http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

您只需要用标题创建一个字典(键:值对,其中键是标题的名称,值是该对的值),然后将该字典传递给.getor .post方法的标题参数。

因此,更具体地针对您的问题:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

回答 1

您还可以执行此操作以为Session对象的所有将来获取设置标头,其中x-test将出现在所有s.get()调用中:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

来自:http : //docs.python-requests.org/en/latest/user/advanced/#session-objects

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects


如何在Django中获取所有请求标头?

问题:如何在Django中获取所有请求标头?

我需要获取所有Django请求标头。根据我的阅读,Django只是将所有内容request.META与大量其他数据一起转储到变量中。获取客户端发送到我的Django应用程序的所有标头的最佳方法是什么?

我将使用这些来构建httplib请求。

I need to get all the Django request headers. From what i’ve read, Django simply dumps everything into the request.META variable along with a lot aof other data. What would be the best way to get all the headers that the client sent to my Django application?

I’m going use these to build a httplib request.


回答 0

根据文档,这 request.META是“包含所有可用HTTP标头的标准Python词典”。如果要获取所有标头,则可以简单地遍历字典。

代码的哪一部分执行此操作取决于您的确切要求。有权访问的任何地方都request应该这样做。

更新资料

我需要在Middleware类中访问它,但是当我对其进行迭代时,除了HTTP标头之外,我还获得了很多其他值。

从文档中:

除了CONTENT_LENGTH和之外CONTENT_TYPE,如上所述,通过将所有字符HTTP都转换META为大写字母,用下划线替换所有连字符并将名称添加HTTP_前缀,将请求中的所有标头都转换为键。

(添加了强调)

HTTP单独获取标题,只需按前缀为的键进行过滤HTTP_

更新2

您能否告诉我如何通过从request.META变量中滤除所有以HTTP_开头并除去开头的HTTP_部分的键来构建标头字典。

当然。这是一种方法。

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

According to the documentation request.META is a “standard Python dictionary containing all available HTTP headers”. If you want to get all the headers you can simply iterate through the dictionary.

Which part of your code to do this depends on your exact requirement. Anyplace that has access to request should do.

Update

I need to access it in a Middleware class but when i iterate over it, I get a lot of values apart from HTTP headers.

From the documentation:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name.

(Emphasis added)

To get the HTTP headers alone, just filter by keys prefixed with HTTP_.

Update 2

could you show me how I could build a dictionary of headers by filtering out all the keys from the request.META variable which begin with a HTTP_ and strip out the leading HTTP_ part.

Sure. Here is one way to do it.

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

回答 1

从Django 2.2开始,您可以使用request.headers访问HTTP标头。从HttpRequest.headers文档中

不区分大小写,类似于dict的对象,该对象提供对请求中所有HTTP前缀的标头(加上Content-Length和Content-Type)的访问。

每个标题的名称在显示时都带有标题框(例如User-Agent)。您可以不区分大小写地访问标头:

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

要获取所有标题,可以使用request.headers.keys()request.headers.items()

Starting from Django 2.2, you can use request.headers to access the HTTP headers. From the documentation on HttpRequest.headers:

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type) from the request.

The name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. You can access headers case-insensitively:

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

To get all headers, you can use request.headers.keys() or request.headers.items().


回答 2

这是另一种实现方法,与上面的Manoj Govindan的答案非常相似:

import re
regex_http_          = re.compile(r'^HTTP_.+$')
regex_content_type   = re.compile(r'^CONTENT_TYPE$')
regex_content_length = re.compile(r'^CONTENT_LENGTH$')

request_headers = {}
for header in request.META:
    if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
        request_headers[header] = request.META[header]

这还将抓取CONTENT_TYPECONTENT_LENGTH请求标头以及HTTP_那些标头。request_headers['some_key]== request.META['some_key']

如果需要包括/省略某些标题,请进行相应的修改。Django在这里列出了一堆,但不是全部:https : //docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

Django请求标头的算法:

  1. -用下划线替换连字符_
  2. 转换为大写。
  3. 前置HTTP_到原请求的所有头,除了CONTENT_TYPECONTENT_LENGTH

每个标头的值都应保持不变。

This is another way to do it, very similar to Manoj Govindan‘s answer above:

import re
regex_http_          = re.compile(r'^HTTP_.+$')
regex_content_type   = re.compile(r'^CONTENT_TYPE$')
regex_content_length = re.compile(r'^CONTENT_LENGTH$')

request_headers = {}
for header in request.META:
    if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
        request_headers[header] = request.META[header]

That will also grab the CONTENT_TYPE and CONTENT_LENGTH request headers, along with the HTTP_ ones. request_headers['some_key] == request.META['some_key'].

Modify accordingly if you need to include/omit certain headers. Django lists a bunch, but not all, of them here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

Django’s algorithm for request headers:

  1. Replace hyphen - with underscore _
  2. Convert to UPPERCASE.
  3. Prepend HTTP_ to all headers in original request, except for CONTENT_TYPE and CONTENT_LENGTH.

The values of each header should be unmodified.


回答 3

request.META.get(’HTTP_AUTHORIZATION’) /python3.6/site-packages/rest_framework/authentication.py

你可以从这个文件中得到…

request.META.get(‘HTTP_AUTHORIZATION’) /python3.6/site-packages/rest_framework/authentication.py

you can get that from this file though…


回答 4

我认为没有简单的方法可以仅获取HTTP标头。您必须遍历request.META字典以获得所需的所有内容。

django-debug-toolbar采用相同的方法显示标题信息。看一下负责检索头信息的文件

I don’t think there is any easy way to get only HTTP headers. You have to iterate through request.META dict to get what all you need.

django-debug-toolbar takes the same approach to show header information. Have a look at this file responsible for retrieving header information.


回答 5

如果要从请求标头获取客户端密钥,则可以尝试以下操作:

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from apps.authentication.models import CerebroAuth

class CerebroAuthentication(BaseAuthentication):
def authenticate(self, request):
    client_id = request.META.get('HTTP_AUTHORIZATION')
    if not client_id:
        raise exceptions.AuthenticationFailed('Client key not provided')
    client_id = client_id.split()
    if len(client_id) == 1 or len(client_id) > 2:
        msg = ('Invalid secrer key header. No credentials provided.')
        raise exceptions.AuthenticationFailed(msg)
    try:
        client = CerebroAuth.objects.get(client_id=client_id[1])
    except CerebroAuth.DoesNotExist:
        raise exceptions.AuthenticationFailed('No such client')
    return (client, None)

If you want to get client key from request header, u can try following:

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from apps.authentication.models import CerebroAuth

class CerebroAuthentication(BaseAuthentication):
def authenticate(self, request):
    client_id = request.META.get('HTTP_AUTHORIZATION')
    if not client_id:
        raise exceptions.AuthenticationFailed('Client key not provided')
    client_id = client_id.split()
    if len(client_id) == 1 or len(client_id) > 2:
        msg = ('Invalid secrer key header. No credentials provided.')
        raise exceptions.AuthenticationFailed(msg)
    try:
        client = CerebroAuth.objects.get(client_id=client_id[1])
    except CerebroAuth.DoesNotExist:
        raise exceptions.AuthenticationFailed('No such client')
    return (client, None)

回答 6

对于它的价值,看来您的意图是使用传入的HTTP请求来形成另一个HTTP请求。有点像网关。有一个出色的模块django-revproxy可以完成此任务。

资料来源很好地参考了如何完成您想做的事情。

For what it’s worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.

The source is a pretty good reference on how to accomplish what you are trying to do.


回答 7

<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}

回答 8

只需从Django 2.2开始使用HttpRequest.headers。以下示例直接取自Django官方文档的请求和响应对象”部分。

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

Simply you can use HttpRequest.headers from Django 2.2 onward. Following example is directly taken from the official Django Documentation under Request and response objects section.

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

如何在Flask中获取HTTP标头?

问题:如何在Flask中获取HTTP标头?

我是python的新手,使用Python Flask并生成REST API服务。

我想检查发送给客户端的授权标头。

但是我找不到在flask中获取HTTP标头的方法。

感谢获得HTTP标头授权的任何帮助。

I am newbie to python and using Python Flask and generating REST API service.

I want to check authorization header which is sent the client.

But I can’t find way to get HTTP header in flask.

Any help for getting HTTP header authorization is appreciated.


回答 0

from flask import request
request.headers.get('your-header-name')

request.headers 行为就像字典,因此您也可以像使用任何字典一样获取标头:

request.headers['your-header-name']
from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

回答 1

请注意,如果标头不存在,则方法之间的区别是

request.headers.get('your-header-name')

将返回None或没有异常,因此您可以像使用它

if request.headers.get('your-header-name'):
    ....

但是以下内容将引发错误

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

你可以通过

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

just note, The different between the methods are, if the header is not exist

request.headers.get('your-header-name')

will return None or no exception, so you can use it like

if request.headers.get('your-header-name'):
    ....

but the following will throw an error

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

You can handle it by

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

回答 2

如果有人试图获取所有已传递的标头,则只需使用:

dict(request.headers)

它为您提供了dict中的所有标头,您实际上可以从中执行任何想要的操作。在我的用例中,由于python API是代理,因此我不得不将所有标头转发到另一个API

If any one’s trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy


回答 3

让我们看看如何在Flask中获取参数,标题和正文。我要在邮递员的帮助下进行解释。

参数项和值反映在API端点中。例如端点中的key1和key2:https : //127.0.0.1/uploadkey1 = value1&key2 = value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

在参数之后,让我们看看如何获​​取标题

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

现在让我们看看如何获​​得身体

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

因此我们使用request.files获取上传的文件,并使用request.form获取文本

Let’s see how we get the params, headers and body in Flask. I’m gonna explain with the help of postman.

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let’s now see how to get the headers:

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let’s see how to get the body

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form