Python to Php Post data Using http request - python

import requests
req = requests.post('http://example.in/phppage.php', data = {'device_id':220,'tank_type':1,'level_pct':78,'water_flow':0,'water_over_flow':0})
print("HTTP Connection Status::"+str(req.status_code))
When I run this code it shows http connection status 404. What is wrong?

# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"
# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"
# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''
# data to be sent to api
data = {'api_dev_key':API_KEY,
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text `enter code here`
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

Related

Telegram Bot URL returns 404

I am using Python for sending message to a telegram group, the URL returns 404. Below is the code:
import requests
from config import API, CHAT_ID
# telegram url
url = "https://api.telegram.org/bot{}".format(API)
print(url)
def send_mess(text):
params = {'chat_id': CHAT_ID, 'text': text}
response = requests.post(url + 'sendMessage', data=params, timeout=20)
return response
if __name__ == '__main__':
d = send_mess('Hi')
print(d)
it looks like the API or the CHAT_ID are not well configured. Even though, I would like to suggest using the telegram library:
pip install python-telegram-bot
import telegram
def send_mess(text):
token = "XXXXXX"
chat_id = "XXXXXX"
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id=chat_id, text=text)
if __name__ == '__main__':
d = send_mess('Hi')
print(d)
There's a simple typo in your code, lets take a look at the following lines:
url = "https://api.telegram.org/bot{}".format(API)
...
response = requests.post(url + 'sendMessage', data=params, timeout=20)
This wel produce an url like;
https://api.telegram.org/bot123456:QWERTYsendMessage
Here, the url is missing an / between the token and the method, would recommend changing;
url + 'sendMessage' to url + '/sendMessage' to get the correct url:
https://api.telegram.org/bot123456:QWERTY/sendMessage
^
Then your code send the message as expected.

Pass files with json payload in single requests to web2py endpoint

I wrote endpoint called foobar in default.py controller of web2py, it looks like
#service.json
def foobar(*args, **vars):
payload = request.vars.student
print(payload)
#Above payload prints [rollNo, firstName, lastName]
#Expected is {"rollNo": 6299857, "FirstName": Prasad, "LastName": Telkikar}
fileObj= request.vars.video
studentActivity = fileObj.file.read()
#Currently I am unable to do it from unit test, but it works from postman
print(f"Student's Roll number = {payload.rollNo} \n FirstName = {payload.firstName}, \n lastName = {payload.lastName}, fileSize = {fileObj.file.tell()}")
#storing studentActivity video to specific location
#Doing business logic
Now I am writing unit test for this endpoint, where i am trying to call this endpoint using requests,
import requests
import unittest
...
class TestStudentsData(unittest.TestCase):
def test_Individual_student(self):
payload = dict(rollNo=6299857, firstName="Prasad", lastName="Telkikar")
url = "http://127.0.0.1:8000/v1/foobar"
header = dict(Authorization="Bearer <Token>")
response = requests.post(url,files={'studentActivity':open("Activity.mp4", 'rb')}, data=payload, headers=headers)
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main(verbosity=2)
Here I am unable to pass student payload as a json.
How can I pass json payload with studentActivity file using requests?
What I tried so far?
I tried both the approaches given in this SO answer.
I read requests documentation where it says "the json parameter is ignored if either data or files is passed" requests documentation
I resolved this problem by adding proper content-type to payload,
import os
...
filePath = os.getcwd()
files = {'studentActivity':open(filePath, "Activity.mp4", 'rb'),
'payload':(None, payload, 'application/json')}
#^^^^^^^^^^^^^^^^^ This was missing
response = requests.post(url,files={'studentActivity':open("Activity.mp4", 'rb')}, data=payload, headers=headers)

No JSON Object could be decoded to missingkids website

I'm not sure why I am receiving this error. There is a decoder.py file in my python folder.
import requests
import json
import common
session = requests.Session()
uri = "http://www.missingkids.com"
json_srv_uri = uri + "/missingkids/servlet/JSONDataServlet"
search_uri = "?action=publicSearch"
child_detail_uri = "?action=childDetail"
session.get(json_srv_uri + search_uri + "&searchLang=en_US&search=new&subjToSearch=child&missState=CA&missCountry=US") #Change missState=All for all states
response = session.get(json_srv_uri + search_uri + "&searchLang=en_US&goToPage=1")
dct = json.loads(response.text)
pgs = int(dct["totalPages"])
print("found {} pages".format(pgs))
missing_persons = {}
The URL http://www.missingkids.com/missingkids/servlet/ returns a 404 Error. Thus, there is no JSON data for Requests to return. Fixing the URL so that it points to a valid destination will allow Requests to return page content.
To make a search for a missing child registered in that website's database, try this URL: http://www.missingkids.com/gethelpnow/search
After every HTTP call you need to check the status code.
Example
import requests
r = requests.get('my_url')
# status code 'OK' is very popular and its numeric value is 200
# note that there are other status codes as well
if r.status_code == requests.codes.ok:
# do your thing
else:
# we have a problem

Uploading a file to a Django PUT handler using the requests library

I have a REST PUT request to upload a file using the Django REST framework. Whenever I am uploading a file using the Postman REST client it works fine:
But when I try to do this with my code:
import requests
API_URL = "http://123.316.118.92:8888/api/"
API_TOKEN = "1682b28041de357d81ea81db6a228c823ad52967"
URL = API_URL + 'configuration/configlet/31'
#files = {
files = {'file': open('configlet.txt','rb')}
print URL
print "Update Url ==-------------------"
headers = {'Content-Type' : 'text/plain','Authorization':API_TOKEN}
resp = requests.put(URL,files=files,headers = headers)
print resp.text
print resp.status_code
I am getting an error on the server side:
MultiValueDictKeyError at /api/configuration/31/
"'file'"
I am passing file as key but still getting above error please do let me know what might I am doing wrong here.
This is how my Django server view looks
def put(self, request,id,format=None):
configlet = self.get_object(id)
configlet.config_path.delete(save=False)
file_obj = request.FILES['file']
configlet.config_path = file_obj
file_content = file_obj.read()
params = parse_file(file_content)
configlet.parameters = json.dumps(params)
logger.debug("File content: "+str(file_content))
configlet.save()
For this to work you need to send a multipart/form-data body. You should not be setting the content-type of the whole request to text/plain here; set only the mime-type of the one part:
files = {'file': ('configlet.txt', open('configlet.txt','rb'), 'text/plain')}
headers = {'Authorization': API_TOKEN}
resp = requests.put(URL, files=files, headers=headers)
This leaves setting the Content-Type header for the request as a whole to the library, and using files sets that to multipart/form-data for you.

HTTP POST using urllib2

IN the code below, I am trying to make a POST of data with urllib2. However, I am getting a HTTP 400 bad request error. Can anyone help me with why this might be the case? The URL is reachable from my computer and all relevant ports are open.
data = {'operation' : 'all'}
results = an.post(an.get_cookie(), 'http://{}:8080/api/v1/data/controller/core/action/switch/update-host-stats'.format(an.TARGET), data)
print results
def post(session_cookie, url, payload):
data = urllib.urlencode(payload)
req = urllib2.Request(url, data)
req.add_header('Cookie','session_cookie=' + session_cookie)
try:
returnedData = urllib2.urlopen(req, data, timeout = 30)
data = json.load(returnedData)
except urllib2.URLError, e:
print e.code
print 'URL ERROR'
return {}
return data
The following code works for me:
import json
import urllib2
import logging
def post_json_request(url, post_data, optional_headers = {}):
"""
HTTP POST to server with json as parameter
#param url: url to post the data to
#param post_data: JSON formatted data
#return: response as raw data
"""
response = ""
try:
req = urllib2.Request(url, post_data, optional_headers)
jsonDump = json.dumps(post_data)
response = urllib2.urlopen(req, jsonDump)
except Exception, e:
logging.fatal("Exception while trying to post data to server - %s", e)
return response
I'm using it in various stubborn platforms that insist to retrieve data on a specific method.
Hope it will help,
Liron

Categories