logo
down
shadow

Python requests: having a space in header for posting


Python requests: having a space in header for posting

By : Dennis Wamelink
Date : October 24 2020, 08:10 AM
wish of those help I found a way to make this work: the problem I was having was due to the use of the urlencode function used in requests. In the requests documentation, it is shown how to go around this default behavior using PreparedRequests: http://docs.python-requests.org/en/master/user/advanced/#prepared-requests
Essentially, instead of using the requests.post() wrapper, make the function calls explicitly. This way, you will be able to control exactly what is sent. In my case, the solution was to do:
code :
import requests
data = {                                                                                                  
    'query': 'GetProcess',                                                                                                                                                                                     
    'getFrom': '2018-12-06 10:10:10.000'
}
s = requests.Session()
req = requests.Request('POST', 'http://'+ipAddress+'/monitor', data=data)
prepped = s.prepare_request(req)
prepped.body = prepped.body.replace("+", " ")
response = s.send(prepped)


Share : facebook icon twitter icon
Posting to CloudApp API (AWS) with Python Requests

Posting to CloudApp API (AWS) with Python Requests


By : Aurie
Date : March 29 2020, 07:55 AM
it helps some times After several days, I finally figured out the (simple) problem. The CloudApp API requires a "GET" request to the "Location" header in Amazon's response.
Pycloudapp was working correctly because it properly authenticated the GET response with return json.load(self.upload_auth_opener.open(request)).
code :
#!/usr/bin/env python

import requests
from collections import OrderedDict
import keyring
import os

last_pic = '/path/to/image.jpg'

USER = 'myemail@email.com'
KEYCHAIN_SERVICE_NAME = 'cloudapp'

# replace with PASS = 'your_password' if you don't use keyring
PASS = keyring.backends.OS_X.Keyring.get_password(KEYCHAIN_SERVICE_NAME, USER)

AUTH_URL = 'http://my.cl.ly'
API_URL = 'http://my.cl.ly/items/new'

s = requests.Session()
s.auth = requests.auth.HTTPDigestAuth(USER, PASS)
s.headers.update({'Accept': 'application/json'})

upload_request = s.get(API_URL)
param_list = []
for key, value in upload_request.json()['params'].items():
    param_list.append((key.encode('utf8'), value.encode('utf8')))
data = OrderedDict(sorted(param_list))

filename = (os.path.basename(last_pic)).encode('utf8')
data['key'] = data['key'].replace(r'${filename}', filename)
files = {'file': (filename, open(last_pic,'rb').read()) }

stuff = requests.post(upload_request.json()['url'], data=data, files=files, allow_redirects=False)

s.get(stuff.headers['Location'])
Posting XML using python requests

Posting XML using python requests


By : Nick Awen
Date : March 29 2020, 07:55 AM
Does that help I am not going to rewrite it all but using str.format, kwargsa and triple quoted a string will make the code a lot less cluttered:
code :
def addVcsRoot(**kwargs):
    headers = {'Content-type': 'application/xml'}

    data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <vcs-root id="{vcsRootId}"  name="{vcsRootName}"
        "vcsName="jetbrains.git" href="/app/rest/vcs-roots/id:"{vcsRootId}"\>""".format(**kwargs)
addVcsRoot(vcsRootId=1234, ......)
def addVcsRoot(vcsRootId, vcsRootName, projectId, projectName, buildName, repoId, teamAdminUser, teamAdminPass)
    headers = {'Content-type': 'application/xml'}

    data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <vcs-root id="{vcsRootId}"  name="{vcsRootName}"
    "vcsName="jetbrains.git" href="/app/rest/vcs-roots/id:"{vcsRootId}"\>"""\
    .format(vcsRootI=vcsRootId, vcsRootName=vcsRootName.....)
Posting form data with requests and python

Posting form data with requests and python


By : James
Date : March 29 2020, 07:55 AM
To fix the issue you can do You have few little mistakes in your code:
Check form's action parameter. Then url = "https://www.yellowpages.com/search" Second parameter is geo_location_terms not geo_locations_terms. You should pass query parameters in requests.get as params not as request data (data).
code :
import requests

search_terms = "Bars"
location = "New Orleans, LA"
url = "https://www.yellowpages.com/search"
q = {'search_terms': search_terms, 'geo_location_terms': location}
page = requests.get(url, params=q)
print(page.url)
https://www.yellowpages.com/search?search_terms=Bars&geo_location_terms=New+Orleans%2C+LA
Missing Host header in HTTP requests from the requests Python library

Missing Host header in HTTP requests from the requests Python library


By : user3153233
Date : March 29 2020, 07:55 AM
This might help you The HOST header is not being added to the request by requests by default. If it is not explicitly added then the decision is delegated to the underlying http module.
See this section of http/client.py:
code :
    if self._http_vsn == 11:
        # Issue some standard headers for better HTTP/1.1 compliance

        if not skip_host:
            # this header is issued *only* for HTTP/1.1
            # connections. more specifically, this means it is
            # only issued when the client uses the new
            # HTTPConnection() class. backwards-compat clients
            # will be using HTTP/1.0 and those clients may be
            # issuing this header themselves. we should NOT issue
            # it twice; some web servers (such as Apache) barf
            # when they see two Host: headers

            # If we need a non-standard port,include it in the
            # header.  If the request is going through a proxy,
            # but the host of the actual URL, not the host of the
            # proxy.

            netloc = ''
            if url.startswith('http'):
                nil, netloc, nil, nil, nil = urlsplit(url)

            if netloc:
                try:
                    netloc_enc = netloc.encode("ascii")
                except UnicodeEncodeError:
                    netloc_enc = netloc.encode("idna")
                self.putheader('Host', netloc_enc)
            else:
                if self._tunnel_host:
                    host = self._tunnel_host
                    port = self._tunnel_port
                else:
                    host = self.host
                    port = self.port

                try:
                    host_enc = host.encode("ascii")
                except UnicodeEncodeError:
                    host_enc = host.encode("idna")

                # As per RFC 273, IPv6 address should be wrapped with []
                # when used as Host header

                if host.find(':') >= 0:
                    host_enc = b'[' + host_enc + b']'

                if port == self.default_port:
                    self.putheader('Host', host_enc)
                else:
                    host_enc = host_enc.decode("ascii")
                    self.putheader('Host', "%s:%s" % (host_enc, port)) 
import requests

response = requests.get("http://httpbin.org/get")
print('Response from httpbin/get')
print(response.json())
print()
print('response.request.headers')
print(response.request.headers)
Response from httpbin/get
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 
 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.20.0'},
 'origin': 'XXXXXX', 'url': 'https://httpbin.org/get'}

response.request.headers
{'User-Agent': 'python-requests/2.20.0', 'Accept-Encoding': 'gzip, deflate', 
 'Accept': '*/*', 'Connection': 'keep-alive'}
Posting image using requests on python

Posting image using requests on python


By : Mario
Date : March 29 2020, 07:55 AM
I hope this helps . You are encoding the whole image into the request parameters, effectively extending the URL by the length of the image.
If you already encoded the image data, use the data parameter:
Related Posts Related Posts :
  • Receiving unsupported operand error while comparing random number and user input.
  • How to wrap the process of creating start_urls in scrapy?
  • How to mark 'duplicated sequence' in pandas?
  • Boolean indexing on multidimensionnal array
  • Unmodified column name index in patsy
  • Cleaner way to unpack nested dictionaries
  • Importing a python module to enable a script to be run from command line
  • Maya Python read and set optionMenu value via variable
  • How can I bind a property to another property in Kivy?
  • Python extracting specific line in text file
  • How to implement n-body simulation with pymunk?
  • Python / matplotlib: print to resolution and without white space / borders / margins
  • Sum up the second value from one dictionary with all values from another dictionary
  • Robot Framework: Open a chrome browser without launching URL
  • Generate inline Bokeh scatterplots in Jupyter using a for loop
  • Group list of dictionaries python
  • Efficient way to apply multiple Boolean mask to set values in a column using pandas
  • Lazy evaluation of a Python dictionary
  • id of xpath is getting changed every time in selenium python 2.7 chrome
  • Matplotlib RuntimeWarning displaying a 3D plot
  • Cannot install pyqt5 for python3.4 on windows 10
  • Gravity Problems
  • Where to position `import` modules inside an class?
  • Python OpenCV: Cannot resize image
  • Print on the same spot in IPython console
  • Disable logging except in tests
  • Writing json to file in s3 bucket
  • Sorting numpy array created by laspy
  • Open an XML file through URL and save it
  • How to build a 2-level dictionary?
  • error installing scipy using pip on windows 10
  • __str__ from my own matrix, python
  • python re how to Extract fields use findall()?
  • how to read a value from text HI file using python?
  • How to use horizontal scrolling in treeview,here i use tree view to make a table
  • Dependant widgets in tkinter
  • Read and write in a JSON file using python 2.x
  • How to fix the function issue while allowing it to be dynamic?
  • Set long strings as default value in class
  • What is the REGEX for any number with a string(letters and punctuations)?
  • pip with several version of python on windows
  • Submitting login form with scrapy
  • How do i edit the favicon in the Browsable API in Django REST framework?
  • multiprocessing.Pool.map_async doesn't seem to... do anything at all?
  • Python Selenium: Stale Element Reference Exception Error
  • Datetime conversion - How to extract the inferred format?
  • Import YAML variables automatically?
  • How to create a powershell shortcut for my python file
  • Python's 'set' operator doesn't work with numpy.nan
  • Pass object fields and one2many fields on same method - Odoo v8
  • Select columns based on column name and location in Pandas
  • Standardizing timeseries in Pandas using interpolation
  • How many tweets can be collected?
  • how format specifier taking value while tuple list is passed
  • How to print a numpy array with data type?
  • Timeout child thread for python3
  • How can I regroup a dataframe and accumulate a colume's values?
  • Bulk Insert into SQL Server with Python not working
  • Removing last rows of each group based on condition in a pandas dataframe
  • Why the css file can not be found in Django template?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org