Cara menggunakan requests.response python

Jadi saya baru-baru ini menemukan perpustakaan hebat ini untuk menangani permintaan HTTP dengan Python; ditemukan di sini http://docs.python-requests.org/en/latest/index.html .

Saya suka bekerja dengannya, tapi saya tidak tahu cara menambahkan header ke permintaan dapatkan saya. Tolong?

Menurut api , header semua bisa diteruskan menggunakan requests.get:

r=requests.get("http://www.example.com/", headers={"content-type":"text"})

Tampaknya cukup mudah, menurut docs pada halaman yang Anda tautkan (penekanan milik saya).

requests.get (url, params = Tidak ada, tajuk = Tidak ada, cookie = Tidak ada, auth = Tidak ada, batas waktu = Tidak ada)

Mengirim permintaan GET. Mengembalikan objek Response.

Parameter:

  • url - URL untuk objek Request baru.
  • params - (opsional) Kamus Parameter GET untuk dikirim dengan Request.
  • header - (opsional) Kamus HTTP Header untuk dikirim dengan Request.
  • cookies - (opsional) objek CookieJar untuk dikirim dengan Request.
  • auth - (opsional) AuthObject untuk mengaktifkan HTTP Auth Basic.
  • timeout - (opsional) Float yang menggambarkan batas waktu permintaan.

Jawaban ini mengajari saya bahwa Anda dapat mengatur tajuk untuk seluruh sesi:

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'})

Bonus: Sesi juga menangani cookie.

It turns out that Dictionary keys are not Object attributes.

Photo by Syd Wachs on Unsplash

In the past week, I and my colleague are learning to use Python programming language at work and decided to write a simple worker with it. The worker is retrieving data from external API with HTTP request and JSON as the response body, if it got success then the data will be stored in our own data storage.

The problem comes when we need to use the cursor, so we can get the next data from the API. The API response will include a cursor field when there is data after the current request. In order to retrieve the next page data, we need to append the cursor to the request’s URL, and we decided to use the cursor field as the identifier.

I google the method about how to check whether an attribute exists in python object and got the result to use Python hasAttribute built-in function. We tried to use that in our function, written like below:

After I tried to run the worker, somehow it always breaks the iteration, even though the cursor field exists within the response object.

Just like many other programmers, the next step to solving that problem is google the solution with a better keyword, this time I search with the keyword: hasattr python not working json object and finally, I got my answer.

It turns out that the dictionary key is not an attribute. The attribute exists within an object created with a Class syntax in Python. So the solution to my problem for checking a key existence inside a dictionary is using a simple in operator.

Finally, my worker can retrieve the next data 😬

Hope this simple note can help you guys solve a similar problem, happy coding!


Saya memiliki API TENANG yang telah saya paparkan menggunakan implementasi Elasticsearch pada contoh EC2 untuk mengindeks kumpulan konten. Saya dapat meminta pencarian dengan menjalankan yang berikut dari terminal saya (MacOSX):

curl -XGET 'http://ES_search_demo.com/document/record/_search?pretty=true' -d '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'

Bagaimana cara mengubah di atas menjadi permintaan API menggunakan python/requestsatau python/urllib2(tidak yakin mana yang harus dituju - telah menggunakan urllib2, tetapi mendengar bahwa permintaan lebih baik ...)? Apakah saya lulus sebagai tajuk atau tidak?

Jawaban:


Menggunakan permintaan :

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Bergantung pada respons apa yang dikembalikan API Anda, Anda mungkin ingin melihat response.textatau response.json()(atau mungkin memeriksanya response.status_codeterlebih dahulu). Lihat dokumen mulai cepat di sini , terutama bagian ini .






Menggunakan permintaan dan json membuatnya mudah.

  1. Panggil API
  2. Dengan asumsi API mengembalikan JSON, parsing objek JSON menjadi json.loadsfungsi menggunakan Python
  3. Lingkari dict untuk mengekstrak informasi.

Modul Permintaan memberi Anda fungsi yang berguna untuk mengulang kesuksesan dan kegagalan.

if(Response.ok): akan membantu Anda menentukan apakah panggilan API Anda berhasil (Kode respons - 200)

Response.raise_for_status() akan membantu Anda mengambil kode http yang dikembalikan dari API.

Di bawah ini adalah contoh kode untuk melakukan panggilan API semacam itu. Juga dapat ditemukan di github . Kode mengasumsikan bahwa API menggunakan otentikasi intisari. Anda dapat melewati ini atau menggunakan modul otentikasi lain yang sesuai untuk mengotentikasi klien yang memohon API.

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()






Jadi, Anda ingin meneruskan data di badan permintaan GET, lebih baik melakukannya di panggilan POST. Anda dapat mencapai ini dengan menggunakan kedua Permintaan.

Permintaan Mentah

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

Contoh panggilan dengan Permintaan

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()



Di bawah ini adalah program untuk menjalankan api sisanya di python-

import requests
url = 'https://url'
data = '{  "platform": {    "login": {      "userName": "name",      "password": "pwd"    }  } }'
response = requests.post(url, data=data,headers={"Content-Type": "application/json"})
print(response)
sid=response.json()['platform']['login']['sessionId']   //to extract the detail from response
print(response.text)
print(sid)