Python post urlencoded from file - python-requests

When i trying to post data from file
headers = {'content-type': 'text/plain'}
files = {'Content': open(os.getcwd()+'\\1.txt', 'rb')}
contentR = requests.post("http://" + domain +"index.php", params=payload, data=files, headers=headers)
I get something like urlencoded string
Content=%3C%3Fphp+echo%28%22Hello+world%22+%29%3B+%3F%3E
instead of
<?php echo("Hello world" ); ?>
How to post data as is in text file?

If you read the docs closely, you can either use the file object:
headers = {'content-type': 'text/plain'}
file = open(os.getcwd()+'\\1.txt', 'rb')
contentR = requests.post("http://" + domain +"index.php", params=payload, data=file, headers=headers)
Or you can just pass a string with the file contents like so:
file_contents = open(os.getcwd() + '\\`.txt', 'rb').read()
contentR = requests.post("http://" + domain +"index.php", params=payload, data=file_contents, headers=headers)
If you pass a dictionary it will always be urlencoded so that is not what you want to do.

Related

How would one send an HTTP POST request?

I'm using lua-http for HTTP requests in my Lua script. I'm trying to find a way to send data as a POST request, similar to the -d option of curl.
I've tried new_from_uri:set_body() but I don't think I'm doing it correctly.
request = require "http.request"
headers, stream = assert(request.new_from_uri("https://example.org"):set_body("body text"))
headers, stream = assert(request.new_from_uri("https://example.org"):go())
body = assert(stream:get_body_as_string())
if headers:get ":status" ~= "200" then
error(body)
end
Could someone show me how to do this properly?
I've decided to use luasocket for this instead. Here is the code I'm using:
http = require "socket.http"
body = "body text"
respbody = {
result, respcode, respheaders, respstatus = http.request {
method = "POST",
url = "https://example.org",
source = ltn12.source.string(body),
headers = {
["content-type"] = "application/json", -- change if you're not sending JSON
["content-length"] = tostring(#body)
},
sink = ltn12.sink.table(respbody)
}
respbody = table.concat(respbody)

Can't Move DriveItem in Mocrosoft Graph

I am using Python to download PDF files from OneDrive to a local folder, and also moving the files to a different folder in OneDrive after they have been downloaded.
I am able to download the files from OneDrive to a local folder, however, I get a 400 response when trying to move (PATCH) the files to another OneDrive Folder.
Here is my successful code to download the files:
download_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}/content'
headers = {'Authorization': 'Bearer ' + json_response['access_token']}
download_url_data = requests.get(download_url, headers=headers)
with open('/Users/Name/Folder/file_name, 'wb') as f:
f.write(download_url_data.content)
Here is my unsuccessful PATCH request to move the files:
move_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}
move_headers = {'Authorization': 'Bearer ' + json_response['access_token'],
'Content-Type' : 'application/json'}
move_body = {'parentReference' : {'id' : '01EV3NG2F6Y2GOVW7775BZO354PUSELRRZ'}}
move_file = requests.patch(move_url, headers=move_headers, data=move_body)
return move_file.status_code
I have followed the documentation here https://learn.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0&tabs=http and I have tried different parentReference id's, but no luck.
Please help! Cheers.
What is the response you're getting (the actual content beside the 400 status code)?
I believe that requests.patch should receive it's data as a string, not a dictionary (json).
Try:
move_file = requests.patch(move_url, headers=move_headers, data=json.dumps(move_body))
And of course don't forget to import json

upload binary file using python requests

I am uploading a file using requests library below is the code:
files = {'file': open(full_file_name, 'rb')}
headers = {"content-type": 'application/x-www-form-urlencoded'}
final_resp = requests.put(loc, files=files, headers=headers)
The problem is some extra contents have been added to the file's start and end point.
The contents added to the start point is:
--b16010ae7646a031a5adc64ac0661e72
Content-Disposition: form-data; name="file"; filename="1016064585-65769268.csv"
The contents added to the endpoint is:
--b16010ae7646a031a5adc64ac0661e72--
But when the same file is uploaded through the postman these problems are not arising.
here is the screenshot of the postman .
The header of the postman is:
application/x-www-form-urlencoded
it may because you use multipart/form to upload file.try use data like code below
data = open(localFilePath, 'rb').read()
headers = {
"Content-Type":"application/binary",
}
upload = requests.put(uploadUrl,data=data,headers=headers)

Dictionary type params in query string

I'm trying to feed the following URL structure into requests:
https://inventory.data.gov/api/action/datastore_search?resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&filters={"City":"Las Vegas","State":"NV"}
I wanted to break up the URL into params, but am having a terrible time getting the filters portion to work properly. I ended up using the below code:
url = 'https://inventory.data.gov/api/action/datastore_search?' \
'resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b&' \
'filters={"City":"' + city + '","State":"' + state + '"}'
resp = requests.get(url=url)
print resp.url
Does anybody know how I can modify this to work with requests like requests.get(url=url, params=params)?
That looks like JSON data. You can convert a Python object to a JSON string with the json module:
import json
import requests
city = 'Las Vegas'
state = 'NV'
filters = {
'City': city,
'State': state
}
params = {
'resource_id': '8ea44bc4-22ba-4386-b84c-1494ab28964b',
'filters': json.dumps(filters)
}
response = requests.get('http://www.example.com/', params=params)
This sends a request to:
http://www.example.com/?filters=%7B%22City%22%3A+%22Las+Vegas%22%2C+%22State%22%3A+%22NV%22%7D&resource_id=8ea44bc4-22ba-4386-b84c-1494ab28964b
where
%7B%22City%22%3A+%22Las+Vegas%22%2C+%22State%22%3A+%22NV%22%7D
is the URL-encoded version of
{"City": "Las Vegas", "State": "NV"}

How to create a new document in Alfresco via REST API?

How to create a certain type of document in Alfresco with using the Rest API. I would like to receive the URL to which to send the request and the list of required parameters. Tried to use http://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference#Create_folder_or_document_.28createDocument.2C_createFolder.29 but it did not work out, because it could not determine which parameters to send to this API
Here are some links to get started with Alfresco + CMIS - These should help to solve your question in general: https://forums.alfresco.com/forum/developer-discussions/alfresco-api/cmis-resources-tutorials-and-examples-03212012-1456
Would use the Rest API, not CIMS
import json
import requests
import os, sys
strUrl = 'http://your.site.com:8080/alfresco/service/api/'
strAuth = ('username', 'password')
strFilename = "somethingtoupload.pdf"
objFile= {'filedata' : open(strFilename,'rb')}
strData={'siteid': 'site','containerid': 'documentlibrary', 'uploaddirectory': 'somefolder'}
result = requests.post (strUrl+'upload',files=objFile,data=strData,auth=strAuth)
print result.status_code
You can create your owen webscript REST and personnalize your processing as you like or you can use this webscript "/api/upload".
To create a document you need to use a query of cmis family. The query looks like:
nodeRef = b544cd67-e839-4c60-a616-9605fa2affb7;
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">' +
'<title>name</title>' +
'<summary>name</summary>' +
'<cmisra:object>' +
'<cmis:properties>' +
'<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">' +
'<cmis:value>type</cmis:value>' +
'</cmis:propertyId>' +
'</cmis:properties>' +
'</cmisra:object>' +
'</entry>';
url: "/../alfresco/service/api/node/workspace/SpacesStore/" + nodeRef + "/children",
method: "POST",
headers: {
"Content-Type": "application/atom+xml;type=entry"
},
xml:xml
name - document name;
type - document type;
nodeRef - folder id in Alfresco.
To create a document in type specify cmis:document. Other queries you can find here:
http://jazzteam.org/en/technical-articles/list-of-alfresco-services/
def post():
cms_repo_url = current_app.config.get("CMS_REPO_URL")
cms_repo_username =current_app.config.get("CMS_REPO_USERNAME")
cms_repo_password =current_app.config.get("CMS_REPO_PASSWORD")
if cms_repo_url is None:
return {
"message": "CMS Repo Url is not configured"
}, HTTPStatus.INTERNAL_SERVER_ERROR
if "upload" not in request.files:
return {"message": "No upload files in the request"}, HTTPStatus.BAD_REQUEST
contentfile = request.files["upload"]
filename = contentfile.filename
files = {'filedata': contentfile.read()}
if filename != "":
try:
url = cms_repo_url + "1/nodes/-root-/children"
document = requests.post(
url,data = request.form,files= files,auth=HTTPBasicAuth(cms_repo_username, cms_repo_password)
)
return (
(
),
HTTPStatus.OK,
)
except UpdateConflictException:
return {
"message": "The uploaded file already existing in the repository"
}, HTTPStatus.INTERNAL_SERVER_ERROR
else:
return {"message": "No upload files in the request"}, HTTPStatus.BAD_REQUEST

Resources