用make doa request do ...

Lesson 3 Making a Request_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
文档贡献者
评价文档:
喜欢此文档的还喜欢
Lesson 3 Making a Request
把文档贴到Blog、BBS或个人站等:
普通尺寸(450*500pix)
较大尺寸(630*500pix)
大小:1.65MB
登录百度文库,专享文档复制特权,财富值每天免费拿!
你可能喜欢Information Quality
Information Quality
Information Quality at the National Archives
As part of our ongoing effort
to provide high-quality ,
the National Archives and Records Administration (NARA) is committed
to ensuring that our information
products are useful, accurate,
clear, complete, and objective.
Making Requests
NARA provides guidance products to the public and the Federal community.
What do I need to know about NARA's information
The Office of Management and Budget (OMB) issued Government-wide guidelines
under section 515 of the Treasury and General Government Appropriations Act
for Fiscal Year 2001 (Pub.L.106-554 to ensure and maximize the quality, objectivity,
utility and integrity of information disseminated by Federal agencies.
Each Federal agency is responsible for issuing its own section 515 guidelines.
Subsequently, NARA has developed its own information quality guidelines.
NARA strives to ensure and maximize the quality, objectivity, utility,
and integrity of the information that we disseminate to the public.
We are committed to integrating the principle of information quality into
every step of development of information, including planning, creation, collection,
maintenance, and dissemination. NARA takes appropriate steps to incorporate
information quality criteria into our information dissemination practices
and ensures that the quality of information that we disseminate is in accordance
with the standards set forth in these guidelines.
The NARA information quality guidelines will become effective on October
1, 2002. The procedures to request corrections will cover information disseminated
on or after October 1, 2002, regardless of when the information was first
disseminated.
NARA's Chief Information Officer is responsible for NARA's compliance with
these guidelines.
What information is NOT subject to NARA's information quality guidelines?
Information that is NOT subject to our information quality guidelines
Archival Records.
Among NARA's responsibilities is to take into
and , for public use, records that have sufficient historical or
other value to warrant their continued preservation by the U.S. Government.
The archival records entrusted to NARA's care have many different creators
including Federal Government agencies, the Congress, the Courts, and Presidential
administrations.
Archival records include books, papers, maps, photographs, electronic records,
or other documentary materials, regardless of physical form or characteristics.
Archival records are excluded from these guidelines because NARA must ensure
the authenticity of the records as they were created, regardless of the
accuracy of the content of the information.
NARA temporarily stores records on behalf of Federal agencies and Members
of Congress. NARA is not responsible for the quality of or correction to
the information content of these records.
Legal Publications. Another of NARA's responsibilities is to publish
the official text of Federal laws, Presidential documents, administrative
regulations and notices, and descriptions of Federal organizations, programs
and activities.
This information is contained in legally-mandated publications of the Office
of the Federal Register:
The texts of these publications are created and submitted by a variety
of Federal entities who are individually responsible for the information
quality of their submissions.
Inter- and Intra-Agency and Operational Information. NARA's information
quality guidelines do not apply to documents intended only for intra-Government
communication or to procedural, operational, policy, and internal manuals
prepared for the management and operations of NARA that are not primarily
intended for public dissemination.
NARA's information quality guidelines do not
apply to responses to requests for agency records under the Freedom of Information
Act, Privacy Act, Federal Advisory Committee Act, or other similar law.
Subpoenas or Adjudicatory Processes. NARA's information quality
guidelines do not apply to information intended to be limited to subpoenas
or adjudicatory processes.
Because there are well-established procedural safeguards and rights to address
the quality of factual allegations and adjudicatory decisions, as well as
to provide persons with an opportunity to contest decisions, NARA's information
quality guidelines do not impose any additional requirements on NARA during
adjudicatory proceedings and do not provide parties to such adjudicatory
proceedings any additional rights of challenge or appeal.
What information IS subject to NARA's information quality guidelines?
Information that IS subject to our information quality guidelines
Information about Archival Records. NARA disseminates information
about the archival records that we hold in several forms including finding
aids, inventories, general information leaflets, research information papers,
and guides.
These products describe the archival records, give context to them, and
identify their location in one of NARA's multiple facilities.
Programs and Services Information. NARA provides information about
our programs and services. For example, NARA mounts exhibits about our holdings,
provides educational materials for grades K-12, and provides records management
information.
We disseminate price lists, catalogs, and other purchasing information for
our products and announcements of events and programs at our facilities
through notices and the .
We also make available information about grants, programs, and funded projects
through the .
Organizational and Management Information. NARA disseminates information
about our structure and organization including employee and office locators,
organizational charts, statements by the Archivist of the United States,
NARA also distributes the
which contains information about NARA's achievements, activities, goals, and products
and the Information Security Oversight Office's (ISOO) Annual Report to the President which
contains information on Federal security classification programs and compiles statistics on
classification and declassification activities Government-wide.
Office of the Federal Register Information. The
makes available information about its official
publications and functions.
How does NARA disseminate this information?
These information products are disseminated in several ways: on paper, microform,
or in electronic form. The primary form used by NARA for electronic dissemination
of information is the NARA web site: .
How can I correct information that is subject to the information quality
guidelines?
Follow the procedure described in these guidelines to correct information
maintained and disseminated by NARA that you believe does not comply with
, published
in the Federal Register in Volume 66, No.189 at 49718 on September
28, 2001, updated in Volume 2, No.67 at 369 on January 3, 2002 (67 F.R.369)
and corrected in Volume 2, No.67 at 8452 on February 22, 2002. These published
guidelines were issued pursuant to Section 515 of the Treasury and General
Government Appropriations Act for FY2001 (Pub. L. 106 -554); or
NARA's information quality guidelines.
What do I need to provide to request a correction?
Your Contact Information. Include your name, mailing address, and
fax number or your name and email address. This information
is needed to respond to your request.
Description of the Information to Correct. Clearly indicate the
information that you believe is in error and should be corrected, as well
as an explanation of how you are affected by the information.
Include the name of the product (e.g., finding aid title, pamphlet number,
web page including URL, title, etc.) where the information is located, the
date of issuance if available, a description of the information to be corrected,
and what corrective action you seek.
Why the Information Should be Corrected. Include specific reasons
why the information should be corrected and, if possible, recommendations
for how it should be corrected.
Recommendations for corrections that are specific and provide evidence to
support the need for correction will enable NARA to provide a satisfactory
Where can I find previous years' information correction requests?
are posted on this website after they have been resolved. Currently
information correction requests received during
are available online.
How can I make a request?
You may submit a written request by letter
or email. NARA will respond in the same form as your request, unless you
indicate otherwise.
Be sure to check:
By letter:
Information Quality
National Archives and Records Administration
NWCC, Room 2400
8601 Adelphi Road
College Park, MD
How will NARA review my request?
Based on a review of the information provided, NARA will determine whether
a correction is warranted, and, if so, what action to take. Any corrective
action will be determined by the nature and timeliness of the information
involved, the significance of the correction, the use of the information,
and the scope of the correction.
How will NARA respond?
NARA will respond to your request by letter, email, or fax.
NARA will respond to requests for correction of information within seven working
days of receipt. If we cannot complete our review of the request within seven
working days, we will inform you that we require more time and provide you with
an estimated decision date.
The response will explain the findings of the review and the actions NARA will
take in response.
Requests for correction concerning information on which NARA has sought
public comment
Information on which NARA may seek public comment includes:
proposed rules (regulations)
other draft analyses supporting proposed rules (e.g., regulatory flexibility
notices (such as information collection notices)
other draft guidance.
Our response to the request for correction will normally be incorporated in
the document that we issue in the matter on which we sought comment. The response
will be provided in this document rather than in a separate communication.
We will consider issuing an earlier response to a request for correction
in cases where:
we determine that an earlier response would not unduly delay issuing
you have shown a reasonable likelihood of suffering actual harm if
we do not resolve the request before we issue the final document.
How can I request reconsideration of a request for correction?
If NARA denies your request for correction, you can appeal the decision within
30 calendar days of receiving notification of the denial.
We will acknowledge receipt of your request for reconsideration within seven
working days of receipt.
Depending on the request, the appeal will be reviewed by the appropriate highest-level
manager at NARA who is not directly involved with the request.
We will respond to your request for reconsideration within 45 calendar days
of the request for reconsideration. Our response will include the decision,
how the decision will be implemented, and within what period of time.
PDF files require the
More information on Adobe Acrobat PDF files is available on our .
About the National Archives &
Information For&
Publications
Orgs & Offices
Want To...
ParticipateNavigation
Quickstart
Eager to get started? This page gives a good introduction in how to get started
with Requests.
First, make sure that:
Requests is
Requests is
Let’s get started with some simple examples.
Make a Request
Making a request with Requests is very simple.
Begin by importing the Requests module:
&&& import requests
Now, let’s try to get a webpage. For this example, let’s get GitHub’s public
&&& r = requests.get('/events')
Now, we have a
object called r. We can
get all the information we need from this object.
Requests’ simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request:
&&& r = requests.post(&http://httpbin.org/post&)
Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple:
&&& r = requests.put(&http://httpbin.org/put&)
&&& r = requests.delete(&http://httpbin.org/delete&)
&&& r = requests.head(&http://httpbin.org/get&)
&&& r = requests.options(&http://httpbin.org/get&)
That’s all well and good, but it’s also only the start of what Requests can
Passing Parameters In URLs
You often want to send some sort of data in the URL’s query string. If
you were constructing the URL by hand, this data would be given as key/value
pairs in the URL after a question mark, e.g. httpbin.org/get?key=val.
Requests allows you to provide these arguments as a dictionary, using the
params keyword argument. As an example, if you wanted to pass
key1=value1 and key2=value2 to httpbin.org/get, you would use the
following code:
&&& payload = {'key1': 'value1', 'key2': 'value2'}
&&& r = requests.get(&http://httpbin.org/get&, params=payload)
You can see that the URL has been correctly encoded by printing the URL:
&&& print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
Note that any dictionary key whose value is None will not be added to the
URL’s query string.
In order to pass a list of items as a value you must mark the key as
referring to a list like string by appending [] to the key:
&&& payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
&&& r = requests.get(&http://httpbin.org/get&, params=payload)
&&& print(r.url)
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
Response Content
We can read the content of the server’s response. Consider the GitHub timeline
&&& import requests
&&& r = requests.get('/events')
&&& r.text
u'[{&repository&:{&open_issues&:0,&url&:&/...
Requests will automatically decode content from the server. Most unicode
charsets are seamlessly decoded.
When you make a request, Requests makes educated guesses about the encoding of
the response based on the HTTP headers. The text encoding guessed by Requests
is used when you access r.text. You can find out what encoding Requests is
using, and change it, using the r.encoding property:
&&& r.encoding
'utf-8'
&&& r.encoding = 'ISO-;
If you change the encoding, Requests will use the new value of r.encoding
whenever you call r.text. You might want to do this in any situation where
you can apply special logic to work out what the encoding of the content will
be. For example, HTTP and XML have the ability to specify their encoding in
their body. In situations like this, you should use r.content to find the
encoding, and then set r.encoding. This will let you use r.text with
the correct encoding.
Requests will also use custom encodings in the event that you need them. If
you have created your own encoding and registered it with the codecs
module, you can simply use the codec name as the value of r.encoding and
Requests will handle the decoding for you.
Binary Response Content
You can also access the response body as bytes, for non-text requests:
&&& r.content
b'[{&repository&:{&open_issues&:0,&url&:&/...
The gzip and deflate transfer-encodings are automatically decoded for you.
For example, to create an image from binary data returned by a request, you can
use the following code:
&&& from PIL import Image
&&& from StringIO import StringIO
&&& i = Image.open(StringIO(r.content))
JSON Response Content
There’s also a builtin JSON decoder, in case you’re dealing with JSON data:
&&& import requests
&&& r = requests.get('/events')
&&& r.json()
[{u'repository': {u'open_issues': 0, u'url': '/...
In case the JSON decoding fails, r.json raises an exception. For example, if
the response gets a 401 (Unauthorized), attempting r.json raises ValueError:
No JSON object could be decoded
Raw Response Content
In the rare case that you’d like to get the raw socket response from the
server, you can access r.raw. If you want to do this, make sure you set
stream=True in your initial request. Once you do, you can do this:
&&& r = requests.get('/events', stream=True)
&requests.packages.urllib3.response.HTTPResponse object at 0x&
&&& r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
In general, however, you should use a pattern like this to save what is being
streamed to a file:
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
Using Response.iter_content will handle a lot of what you would otherwise
have to handle when using Response.raw directly. When streaming a
download, the above is the preferred and recommended way to retrieve the
Note: Custom headers are given less precedence than more specific sources of information. For instance:
Authorization headers will be overridden if credentials are passed via the auth parameter or are specified in a .netrc accessible in the environment.
Authorization headers will be removed if you get redirected off-host.
Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
Content-Length headers will be overridden when we can determine the length of the content.
Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.
More complicated POST requests
Typically, you want to send some form-encoded data — much like an HTML form.
To do this, simply pass a dictionary to the data argument. Your
dictionary of data will automatically be form-encoded when the request is made:
&&& payload = {'key1': 'value1', 'key2': 'value2'}
&&& r = requests.post(&http://httpbin.org/post&, data=payload)
&&& print(r.text)
&key2&: &value2&,
&key1&: &value1&
There are many times that you want to send data that is not form-encoded. If
you pass in a string instead of a dict, that data will be posted directly.
For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:
&&& import json
&&& url = '/some/endpoint'
&&& payload = {'some': 'data'}
&&& r = requests.post(url, data=json.dumps(payload))
POST a Multipart-Encoded File
Requests makes it simple to upload Multipart-encoded files:
&&& url = 'http://httpbin.org/post'
&&& files = {'file': open('report.xls', 'rb')}
&&& r = requests.post(url, files=files)
&&& r.text
&files&: {
&file&: &&censored...binary...data&&
You can set the filename, content_type and headers explicitly:
&&& url = 'http://httpbin.org/post'
&&& files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
&&& r = requests.post(url, files=files)
&&& r.text
&files&: {
&file&: &&censored...binary...data&&
If you want, you can send strings to be received as files:
&&& url = 'http://httpbin.org/post'
&&& files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
&&& r = requests.post(url, files=files)
&&& r.text
&files&: {
&file&: &some,data,to,send\\nanother,row,to,send\\n&
In the event you are posting a very large file as a multipart/form-data
request, you may want to stream the request. By default, requests does not
support this, but there is a separate package which does -
requests-toolbelt. You should read
for more details about how to use it.
For sending multiple files in one request refer to the
Response Status Codes
We can check the response status code:
&&& r = requests.get('http://httpbin.org/get')
&&& r.status_code
Requests also comes with a built-in status code lookup object for easy
reference:
&&& r.status_code == requests.codes.ok
If we made a bad request (a 4XX client error or 5XX server error response), we
can raise it with
&&& bad_r = requests.get('http://httpbin.org/status/404')
&&& bad_r.status_code
&&& bad_r.raise_for_status()
Traceback (most recent call last):
File &requests/models.py&, line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
But, since our status_code for r was 200, when we call
raise_for_status() we get:
&&& r.raise_for_status()
All is well.
The dictionary is special, though: it’s made just for HTTP headers. According to
, HTTP Header names
are case-insensitive.
So, we can access the headers using any capitalization we want:
&&& r.headers['Content-Type']
'application/json'
&&& r.headers.get('content-type')
'application/json'
It is also special in that the server could have sent the same header multiple
times with different values, but requests combines them so they can be
represented in the dictionary within a single mapping, as per
& A recipient MAY combine multiple header fields with the same field name
& into one “field-name: field-value” pair, without changing the semantics
& of the message, by appending each subsequent field value to the combined
& field value in order, separated by a comma.
If a response contains some Cookies, you can quickly access them:
&&& url = '/some/cookie/setting/url'
&&& r = requests.get(url)
&&& r.cookies['example_cookie_name']
'example_cookie_value'
To send your own cookies to the server, you can use the cookies
parameter:
&&& url = 'http://httpbin.org/cookies'
&&& cookies = dict(cookies_are='working')
&&& r = requests.get(url, cookies=cookies)
&&& r.text
'{&cookies&: {&cookies_are&: &working&}}'
Redirection and History
By default Requests will perform location redirection for all verbs except
We can use the history property of the Response object to track redirection.
list contains the
objects that were created in order to
complete the request. The list is sorted from the oldest to the most recent
For example, GitHub redirects all HTTP requests to HTTPS:
&&& r = requests.get('')
'/'
&&& r.status_code
&&& r.history
[&Response [301]&]
If you’re using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
redirection handling with the allow_redirects parameter:
&&& r = requests.get('', allow_redirects=False)
&&& r.status_code
&&& r.history
If you’re using HEAD, you can enable redirection as well:
&&& r = requests.head('', allow_redirects=True)
'/'
&&& r.history
[&Response [301]&]
timeout is not a time limit on the enti
rather, an exception is raised if the server has not issued a
response for timeout seconds (more precisely, if no bytes have been
received on the underlying socket for timeout seconds).
Errors and Exceptions
In the event of a network problem (e.g. DNS failure, refused connection, etc),
Requests will raise a
exception.
In the rare event of an invalid HTTP response, Requests will raise an
exception.
If a request times out, a
exception is
If a request exceeds the configured number of maximum redirections, a
exception is raised.
All exceptions that Requests explicitly raises inherit from
Ready for more? Check out the

我要回帖

更多关于 make do 的文章

 

随机推荐