Python Urllib form help - python

I am trying to make a program that will access http://mailfreeonline.com/free_anonymous_mail and send me an email. This is what I have so far, it says there is a syntax error with the second colon?
import urllib
params = urllib.urlencode(
{'tomailget': 'myemail#gmail.com',
'fromnameget': 'Matt'
'frommailget': 'test#test.com'
'subjectget': 'Subject'
'messageget': 'Message' })
f = urllib.urlopen("http://www.mailfreeonline.com/free_anonymous_mail", params)

You have to add comma after each parameter, you forgot to do that
params = urllib.urlencode( {'tomailget': 'myemail#gmail.com',
'fromnameget': 'Matt',
'frommailget': 'test#test.com',
'subjectget': 'Subject',
'messageget': 'Message' })

I don't see commas between the elements in the dictionary
{'tomailget': 'myemail#gmail.com',
'fromnameget': 'Matt'**,**
'frommailget': 'test#test.com'**,**
'subjectget': 'Subject'**,**
'messageget': 'Message' })

Related

Gravity form API with python

The documentation of the API is here, and I try to implement this line in python
//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}
But when I try to do with python in the following code, I got an error:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'
r = session.get(url)
print(r.content)
The error message is :
ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.
One solution is to parameterize the url:
import requests
import json
url = 'https://localhost/wp-json/gf/v2/entries'
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
headers = {'Content-type': 'application/json'}
response = session.get(url, params=params, headers=headers)
print(response.json())
But in the retrieved entries, the data is not filtered with the specified date.
In the official documentation, they gave a date in this format "09/01/2023", but in my dataset, the format is: "2023-01-10 19:16:59"
Do I have to transform the format ? I tried a different format for the date
date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")
What alternative solutions can I test ?
What if you use urllib.parse.urlencode function, so your code would looks like:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
import urllib.parse
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'
r = session.get(url)
print(r.content)
hope that helps
I had the same problem and found a solution with this code:
params = {
'search': json.dumps({
'field_filters': [
{ 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
],
'mode': 'all'
})
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement
I'm not really sure what permitted it to work as I'm an absolute beginner with Python, but I found that you need double quotes in the URL ( " ) instead of simple quotes ( ' ), so the solution by William Castrillon wasn't enough.
As for the date format, Gravity Forms seems to understand DD/MM/YYYY. It doesn't need a time either.

Opensubtitles api python data is not a dictionary

the documentation:
https://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC
from xmlrpc.client import ServerProxy
url = 'http://api.opensubtitles.org/xml-rpc'
server = ServerProxy(url)
token = server.LogIn('username', 'Password', 'eng', 'TemporaryUserAgent')['token']
data = server.SearchSubtitles(token, [{'sublanguageid': 'english', 'query': 'Movie Name'}])
I print data and it has IDSubtitleFile in it. but then I try
id_subtitle_file = data.get('IDSubtitleFile')
and it prints None
I have seen it done this way too
id1= data.get('data')
subtitle_id = id1.get('IDSubtitleFile'))
but this throws 'list' object has no attribute 'get'
what am I doing wrong?
Please check the API documentation: here
The search request response structure:
{
status: ...
data: [ # <-- array
...records...
]
}
Code sample below:
from xmlrpc.client import ServerProxy
server = ServerProxy("http://api.opensubtitles.org/xml-rpc")
token = server.LogIn('username', 'pass', 'eng', 'TemporaryUserAgent')['token']
response = server.SearchSubtitles(token,
[{'sublanguageid': 'english', 'query': 'Movie Name'}]
)
for record in response["data"]:
print(record["IDSubtitleFile"])

problems with requests in python list

I am going to post phone in the app but I am getting error again and again. Because the structure of the post looks like that
data = {
'login': 'login',
'password': 'password',
'data': '[{"user_id": "user_id","text": "key"}]'
}
response = requests.post('url', data=data)
the problem with this code is that user_id and key because they are not default values they can be different. if I remove apostrophe from the list. Error occurs Array is not Json. If I put this like that
data = [
{
'login': 'login',
'password': 'password',
'data': {"user_id": user_id, "text": key}
}
]
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
response = requests.post('url', json=data, headers=headers)
It throws another error Login or Password is null. How can I solve this problems any help plz? thank you in advance!
If I understand the question correctly, you want to replace the hard-coded user id and key with values from a pair of variables. This shouldn't require any change in the structure of the payload. Just try
import json
user_id = "..."
key = "..."
request_data = [{"user_id": user_id, "text": key}]
data = {
'login': 'login',
'password': 'password',
'data': json.dump(request_data)
}
response = requests.post('url', data=data)

How to create a MR using GitLab API?

I am trying to create a merge request using the GitLab Merge Request API with python and the python requests package. This is a snippet of my code
import requests, json
MR = 'http://www.gitlab.com/api/v4/projects/317/merge_requests'
id = '317'
gitlabAccessToken = 'MySecretAccessToken'
sourceBranch = 'issue110'
targetBranch = 'master'
title = 'title'
description = 'description'
header = { 'PRIVATE-TOKEN' : gitlabAccessToken,
'id' : id,
'title' : title,
'source_branch' : sourceBranch,
'target_branch' : targetBranch
}
reply = requests.post(MR, headers = header)
status = json.loads(reply.text)
but I keep getting the following message in the reply
{'error': 'title is missing, source_branch is missing, target_branch is missing'}
What should I change in my request to make it work?
Apart from PRIVATE-TOKEN, all the parameters should be passed as form-encoded parameters, meaning:
header = {'PRIVATE-TOKEN' : gitlabAccessToken}
params = {
'id' : id,
'title' : title,
'source_branch' : sourceBranch,
'target_branch' : targetBranch
}
reply = requests.post(MR, data=params, headers=header)

Pushover Acknowlage in python

Im having some issue trying to get ackknowalgemtns working with python.
thus far my code posts the message and gets the JSON sting in return but now i need a way to get the receipt out of the string
import requests
app_token = 'app token'
user_token = 'user token'
title = 'TEST MESSGAE'
text = 'text for polling'
params = {
'token': app_token,
'user': user_token,
'title': title,
'message': text,
'retry': 30,
'expire': 180,
'priority': 2,
'sound': 'siren',
}
msg = requests.post('https://api.pushover.net/1/messages.json', data=params)
print "POSTed message"
print msg.json()
output is
POSTed message
{u'status': 1, u'receipt': u'riD7NEukZsiDQpjhiNppphYnpue8uK', u'request': u'ef5f42d568e966cbf3d2b28c6579397c'}
The parameter is a case-sensitive, 30 character string containing the character set [A-Za-z0-9].
would this be a REGEX job ?
Because it's json type, so you can just use json module to load the data as a dict. For example if you have some json
data like this:
'{"message":"Hello there, wayfaring stranger"}'
Then you can use json.loads() function to load it as a dict like this:
>>> a = '{"message":"Hello there, wayfaring stranger"}'
>>> import json
>>> d = json.loads(a)
>>> d.items()
dict_items([('message', 'Hello there, wayfaring stranger')])
>>>
As you can see, a is string, but d is a dict. And now, 'Hello there, wayfaring stranger' is the value of key 'message'.
But msg.json() can auto covert the json data to dict, so you don't need json module here. So if you want to get 'ef5f42d568e966cbf3d2b28c6579397c', you can simply do something like this:
json_data = msg.json()
print json_data['request']

Categories