Getting unecessary quotation marks in Python 2 - python

In a whole context of trying to combine 2 APIs, I need to "combine" two functions results so that everything is more organized.
def descr():
return 88
def name():
return 'Account',descr()
When I print name(), I get this ('Account', 88). Problem with that format is that I can't use this result later in my script.
Here is the whole script :
import requests
import json
url = "https://proxy6.net/api/xxx/getproxy"
def descr():
return 88
def name():
return 'Account',descr()
querystring = {"descr":descr()}
headers = {
'Cache-Control': "no-cache",
'Postman-Token': "xxxx"
}
response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json()
for value in data['list'].values():
host = value['host']
port = value['port']
url = "https://api.multiloginapp.com/v1/profile/create"
querystring = {"token":"xxx"}
payloadobj = {
"generateZeroFingerprintsData": True,
"name": name(),
"OS": "MacOS",
"platform": "MacIntel",
"browserType": "mimic",
"proxyHost": host,
"proxyPort": port,
"proxyIpValidation": False,
"proxyType": "socks5",
"maskFonts": True,
"disablePlugins": True,
"disableWebrtcPlugin": True,
"disableFlashPlugin": True,
"canvasDefType": "noise",
"hardwareConcurrency": 2,
"langHdr": "en-US,en;q=0.8",
"timeZone": "US/Eastern",
"audio": {
"noise": True
},
"geolocation": {
"permitType": "block"
},
"mediaDevices": {
"audioInputs": 1,
"audioOutputs": 1,
"videoInputs": 1
},
"webgl": {
"noise": True
},
"webRtc": {
"type": "block"
},
"shared": False
}
payload = json.dumps(payloadobj)
headers = {
'Content-Type': "application/json",
'Cache-Control': "no-cache",
'Postman-Token': "xxx"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
I want the name value in the JSON query above to be the result of name + descr, but it won't work with that returned format.

Looks like you need.
def descr():
return 88
def name():
return '{} {}'.format('Account', descr())
print(name())
Output:
Account 88

name() is returning a tuple object not a string. To return a string you could change it to:
def name():
return "Account {}".format(descr())

If you are using python3.6 or later you can:
def descr():
return 88
def name():
return f"Account {descr()}"

Related

Django return JsonResponse and continue

I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not
def paytes(request):
payload ={
"USERID": code_id,
"MSISDN": serviceCode,
"MSGTYPE": type_msg,
"USERDATA": text,
"SESSIONID": session_id,
"MSG": response,
}
print('MSG: ',response)
# headers = {
# 'Content-Type': 'application/json'
# }
# response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
return JsonResponse(payload)
url = 'https://prod.theteller.net/v1.1/transaction/process'
transaction_id = random.randint(100000000000, 999999999999)
amounte = "000000000080"
amount = str(amounte)
data = {
"amount" :amount,
"processing_code" : "000200",
"transaction_id" : transaction_id,
"desc" : "Mobile Money Payment Test",
"merchant_id" : "TTM-00000727",
"subscriber_number" : "233244491909",
"r-switch" : "MTN",
}
encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=') # change this as well
headers = {
'Content-Type': 'application/json',
'Authorization': f'Basic {encoded.decode("utf-8")}',
'Cache-Control': 'no-cache'
}
res = requests.post(url, data=json.dumps(data), headers=headers)
print(res.text)
response_data = res.json()
status = response_data["status"]
print(response_data)
print(status)
return HttpResponse(res)
All the code after the first return statement is executed won't be executed, so if you want to return both of those variables then put them inside the same dictionary and return that:
return_val = {}
return_val['payload'] = payload
return_val['response'] = res
return JsonResponse(return_val)

How to get from POST request .getresponse()(json) specific thing("access_token": value)? (using import http.client)

I get json as response as:
{"access_token":"QVQ6YmNlZjI0fdsfsFSZiLWE0OTgtZGUwMTJhMDdjMjYz","token_type":"Bearer","expires_in":7776000}
How do I write to a variable just one value from response?
Need "access_token" key value (= QVQ6YmNlZjI0fdsfsFSZiLWE0OTgtZGUwMTJhMDdjMjYz)?
Also should I better use import requests and if so, how this code would look in there?
Code: (New code with title fixed problem)
import http.client
import json
#Request Client Credential Grant (CCG) token
conn = http.client.HTTPSConnection("sandbox.handelsbanken.com")
payload = "client_id=45325132-fsafsa-saczx&grant_type=client_credentials&scope=AIS"
headers = {
'Accept': "application/json",
'Content-Type': "application/x-www-form-urlencoded",
'content-type': "application/x-www-form-urlencoded",
'accept': "application/json"
}
conn.request("POST", "/openbanking/oauth2/token/1.0", payload, headers)
res = conn.getresponse()
data = res.read()
y = json.loads(data)
access_token = y.get("access_token", None)
#print(data.decode("utf-8"))
Next problem is implementing it in new headers
payload = "{\"access\":\"ALL_ACCOUNTS\"}"
headers = { 'X-IBM-Client-Id': "REPLACE_THIS_VALUE", '
Authorization': "Bearer "+access_token, '
Country': "REPLACE_THIS_VALUE", '
TPP-Transaction-ID': "REPLACE_THIS_VALUE", '
TPP-Request-ID': "REPLACE_THIS_VALUE", '
content-type': "application/json", '
accept': "application/json" }
Do I do it like this?
I understood that I can't comprehend how do another thing with json..
{
"accounts": [
{
"accountId": "ae57e780-6cf3-11e9-9c41-e957ce7d7d69",
"iban": "SE5460000000000403333911",
"bban": "403333911",
"currency": "SEK",
"accountType": "Allkortskonto",
"bic": "HANDSESS",
"clearingNumber": "6295",
"ownerName": "Bo Bankkund",
"_links": {
"transactions": {
"href": "https://sandbox.handelsbanken.com/openbanking/psd2/v2/accounts/ae57e780-6cf3-11e9-9c41-e957ce7d7d69/transactions"
}
}
},
{
"accountId": "ae5835a0-6cf3-11e9-9c41-e957ce7d7d69",
"iban": "SE8160000000000401975231",
"bban": "401975231",
"currency": "SEK",
"accountType": "Allkonto Ung",
"bic": "HANDSESS",
"clearingNumber": "6295",
"name": "Almas konto",
"ownerName": "Alma Bankkund",
"_links": {
"transactions": {
"href": "https://sandbox.handelsbanken.com/openbanking/psd2/v2/accounts/ae5835a0-6cf3-11e9-9c41-e957ce7d7d69/transactions"
}
}
}
]
}
How to get first "accountId" key value in a variable?
1.How do I write to a variable just one value from response?:
data = res.read()
y = json.loads(data) #transforms "data" to json
access_token = y.get("access_token", None) #access "access_token" value and if there's no value makes it none with "None"
Next problem is implementing it in new headers:
headers = { 'X-IBM-Client-Id': "REPLACE_THIS_VALUE", '
Authorization': "Bearer "+access_token, '
Country': "REPLACE_THIS_VALUE", '
TPP-Transaction-ID': "REPLACE_THIS_VALUE", '
TPP-Request-ID': "REPLACE_THIS_VALUE", '
content-type': "application/json", '
accept': "application/json" }
How to get first "accountId" key value in a variable?
data = res.read()
y = json.loads(data)
accounts = y["accounts"][0] # saves in variable first accounts array elements
accountId = accounts["accountId"] #from accounts variable takes "accountId" value

Returning values from dictionary

import requests #package required to handle API requests
import json #built in package to handle JSON
import os #accesing variables from .bash_profile
i= 0 #const required to iteration of loop
f = open("/mnt/c/_KOD_/project/JSON/output.txt", "a", encoding="UTF-8" )
fraza=str
id_category=int
url = os.environ.get("PROD_LB")
print("Provide search phrase :")
input(fraza)
print("provide category:")
input(id_category)
payload = "\r\n{\r\n \"criteria\": {\r\n \"product_list.show\": true,\r\n \"product_list.show_if_below\": -1,\r\n \"product_list.limit\": -1,\r\n \"product_sum.show\": true,\r\n \"query.phrase\": \"", fraza ,"\",\r\n \"category.id_or_deeper\": [\"", id_category,"diod \"]\r\n }\r\n}"
headers = {
'Content-Type': "application/json",
'User-Agent': "PostmanRuntime/7.18.0",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "75924d05-2bd0-4133-aed7-515aa644a535,bfdc06e9-6142-4822-a919-81390ba871e4",
'Host': "search.tme.eu:8443",
'Accept-Encoding': "gzip, deflate",
'Content-Length': "230",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
ress = json.loads(response.text)
list = ress["product_list"]
a = list.__len__() #no longer needed in for loop.
# this part below is quite junky and i have no clue how to revive it...
**For list, value in list.items() :
# while i < a:
f.write(list["symbol"])
f.write("\r\n")
# i +=1
f.close**
Payload above genere JSON response that look like
{
"request_id": 4454370058,
"product_list": [
{
"score": 19993,
"symbol": "M22-ES-MS2",
"id": 346733
},
.
.
.
{
"score": 19989,
"symbol": "M22-D-R-X0/KC11/I",
"id": 94432
}
],
"do_show": true,
"do_show_list": {
"do_show_products": true,
"do_show_parameters": false,
"do_show_parameter_values": false,
"do_show_flags": false
}
}
My goal is to save part of response to txt file that look like:
M22-ES-MS2
M22-D-R-X0/KC11/I
I was able to do this by saving respones to JSON file and from that to save to final format... however that was not optimal..
Currently im stuck with either of 2 errors
When i try to do this via While loop im receving :
in _encode_params
for k, vs in to_key_val_list(data):
ValueError: too many values to unpack (expected 2)
or after reading THIS
im stuck with
File "/mnt/c/_KOD_/project/JSON/request.py", line 39
For list, value in list.items() :
^
SyntaxError: invalid syntax
As I have no clue how this should work.
This is my most advanced python code I have ever created in my 3 weeks of programming.
you can load the json data using the json library and then just iterate over the products list printing the symbols.
data = """{
"request_id": 4454370058,
"product_list": [
{
"score": 19993,
"symbol": "M22-ES-MS2",
"id": 346733
},
{
"score": 19989,
"symbol": "M22-D-R-X0/KC11/I",
"id": 94432
}
],
"do_show": true,
"do_show_list": {
"do_show_products": true,
"do_show_parameters": false,
"do_show_parameter_values": false,
"do_show_flags": false
}
}"""
import json
json_data = json.loads(data)
for product in json_data['product_list']:
print(product['symbol'])
OUTPUT
M22-ES-MS2
M22-D-R-X0/KC11/I
list is a reserved name in python, try changing the name list to something else.
You can put key, value instead of list, value.
Also the For should be lower case for.

Post created using create image share API with /ugcPosts endpoint is not visible on linkedin on my timeline

I have implemented all three steps for sharing an image post on linkedin using create image share api described below. But created posts are not visible on my linkedin feed/posts or recent activities.
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin#create-an-image-share
First time I created the post is visible using API and it returned {"id":"urn:li:share:6521244543193575424"}
Posted Visible post url:
https://www.linkedin.com/feed/update/urn:li:share:6520269375554060288/
Second time onwards created with same code below returns similar response with created post id and with 201 created status code but post is not visible on linkedin.
For example this post
https://www.linkedin.com/feed/update/urn:li:share:6521027773560119296
I checked my linkedin profile but couldn't find my posts any where.
Code for Final function for posting I am using(3rd step for creating image share using the documentation link above) :
def share_on_linkedin(self, asset, title, description):
# asset = "urn:li:digitalmediaAsset:C5122AQEAatG9rZ7MhQ"
headers = {
'Content-Type':'application/json',
'X-Restli-Protocol-Version': '2.0.0',
'Authorization': 'Bearer '+Constant.ACCESS_TOKEN
}
payload = {
"author": "urn:li:person:leRbOTCFKK",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": description
},
"shareMediaCategory": "IMAGE",
"media": [
{
"status": "READY",
"description": {
"text": "Center stage!"
},
"media": asset,
"title": {
"text": title
}
}
]
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
try:
data = json.dumps(payload, sort_keys=True, indent=4)
url = "https://api.linkedin.com/v2/ugcPosts"
response = requests.post(url , headers=headers, data=data )
print response.text
result = json.loads(response.text)
if response.status_code==200 or response.status_code==201:
print response.text
print response.headers
posted_url = "https://www.linkedin.com/feed/update/"+result['id']
print posted_url
return True, posted_url
return False, None
except Exception as e:
print e
Output:
{"id":"urn:li:share:6521245116978552832"}
{'Content-Length': '41', 'X-RestLi-Protocol-Version': '2.0.0', 'X-Li-Pop': 'prod-tmu1', 'X-LI-ResponseOrigin': 'RGW', 'X-RestLi-Id': 'urn:li:share:6521245116978552832', 'X-LI-UUID': 'aKr30Z+1kxWAo4kEzioAAA==', 'X-LI-Route-Key': '"b=SB83:g=115:u=3:i=1554785994:t=1554872227:s=AQH26er48VUD_YiXQIgAqujebI53eswQ"', 'X-Li-Fabric': 'prod-lsg1', 'Connection': 'keep-alive', 'Location': '/ugcPosts/urn%3Ali%3Ashare%3A6521245116978552832', 'Set-Cookie': 'lidc="b=SB83:g=115:u=3:i=1554785994:t=1554872227:s=AQH26er48VUD_YiXQIgAqujebI53eswQ"', 'Date': 'Tue, 09 Apr 2019 04:59:55 GMT', 'X-LI-Proto': 'http/1.1', 'Content-Type': 'application/json'}
Posted url constructed from above successful response is:
https://www.linkedin.com/feed/update/urn:li:share:6521245116978552832
But this post is not visible.
Can anybody help me with this.
Thanks!
You may need to verify your media asset is available and ready to be posted before submitting your ugcPosts request.
After you've uploaded your image binary, submit a request to the /assets API and check the status is AVAILABLE
GET https://api.linkedin.com/v2/assets/C5122AQEAatG9rZ7MhQ
Use python to share text and image on LinkedIn API
Python Linkedin, How to share content on user's wall
i#mage upload linkedin api
code start from here
def imageShare(request):
if request.FILES.getlist('media') and request.POST['postText']:
# step 1
try:
new_asset.clear()
except:
pass
access_token = token[0]
h = {
'Authorization': 'Bearer ' + str(access_token),
'Content-Type': 'multipart/form-data',
'X-Restli-Protocol-Version': '2.0.0',
}
data = {
"registerUploadRequest": {
"recipes": [
"urn:li:digitalmediaRecipe:feedshare-image"
],
"owner": "urn:li:person:mUIlTwceuD",
"serviceRelationships": [
{
"relationshipType": "OWNER",
"identifier": "urn:li:userGeneratedContent"
}
]
}
}
z = requests.post('https://api.linkedin.com/v2/assets?action=registerUpload', headers=h, data=json.dumps(data))
print(z.text)
aa = z.json()['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest'][
'uploadUrl']
shareurl.append(aa)
# print(shareurl)
bb = z.json()['value']['asset']
asset = bb.replace('urn:li:digitalmediaAsset:', '')
new_asset.append(asset)
# step 2 upload binary image
upload_url = str(aa)
postText = request.POST['postText']
image = request.FILES.getlist('media')
print('blank image', image)
for i in image:
headers = {
'Authorization': 'Bearer ' + str(access_token),
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'image/jpeg,image/png,image/gif',
}
response = requests.post(upload_url, headers=headers, data=i.read())
he = {
'Authorization': 'Bearer ' + str(access_token),
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
}
ab = requests.get('https://api.linkedin.com/v2/assets/' + str(new_asset[0]), headers=he)
print('submittttttttt', ab.content)
# return redirect('http://127.0.0.1:8000/social_app/index/')
#
#
#
# def index(request):
headers = {
'content-type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + str(access_token),
}
data = {
"author": "urn:li:person:mUIlTwceuD",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": postText
},
"shareMediaCategory": "IMAGE",
"media": [
{
"status": "READY",
"description": {
"text": "Center stage!"
},
"media": "urn:li:digitalmediaAsset:" + str(new_asset[0]),
"title": {
"text": "LinkedIn Talent Connect 2018"
}
}
]
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
z = requests.post('https://api.linkedin.com/v2/ugcPosts', headers=headers, data=json.dumps(data))
print(z.text)
return HttpResponse('Image shared')
else:
if request.method == 'POST':
post = request.POST['postText']
print("post = ", post)
sub = {
"author": "urn:li:person:mUIlTwceuD",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": post,
},
"shareMediaCategory": "NONE"
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
h = {
'Authorization': 'Bearer ' + str(access_token),
'Content-Type': 'text/plain',
'content-type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0',
}
a = requests.post('https://api.linkedin.com/v2/ugcPosts', headers=h, data=json.dumps(sub))
print(a, a.content, a.text, a.json())
return render(request, 'post.html', {})
return HttpResponse('text sent')

Update Sharepoint 2013 using Python3

I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type

Categories