I am not able to get JSON response when I try to run python core-backup.py file: In code FB_SHORT_ACCESS_TOKEN and FB_LONG_ACCESS_TOKEN are same.
core-backup.py :
import os
from os.path import join
import requests
def refresh_short_token():
"""
Refresh short access token
"""
request_url = FB_URL + 'oauth/access_token'
request_payload = {
'grant_type': 'fb_exchange_token',
'client_id': FB_APP_ID,
'client_secret': FB_APP_SECRET,
'fb_exchange_token': FB_SHORT_ACCESS_TOKEN
}
response = REQ_SESSION.get(request_url, params=request_payload).json()
# dotenvfile = find_dotenv()
# load_dotenv(dotenvfile)
# dotenv.set_key(dotenvfile, "FB_LONG_ACCESS_TOKEN", response['access_token'])
FB_LONG_ACCESS_TOKEN = response["access_token"]
# PAYLOAD['access_token'] = dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN")
PAYLOAD['access_token'] = FB_LONG_ACCESS_TOKEN
'''
TODO: refresh_long_token()
A function to refresh the long term access token
Current validity: 60 days
'''
def get_feed():
"""
Fetch feed
"""
request_url = FB_URL + LTTK_GROUP_ID + '/feed'
response = REQ_SESSION.get(request_url, params=PAYLOAD)
if response.status_code == 400:
refresh_short_token()
print(response.json())
return response.json()
def main():
"""
Fetch posts from a Facebook group and populate in database
"""
get_feed()
if __name__ == "__main__":
main()
I am getting UnicodeDecodeError in windows7 after running core-backup.py
file. How to fix this issue.
See screenshot for more clarity:
Entire code of file can be found out here:
https://gist.github.com/anonymous/2ab9e023d631a7cc4dad15237104ee34
It appears that your code page is set to cp437. Try setting python output to utf-8 by entering the following line in your terminal before running your python script.
set PYTHONIOENCODING=UTF-8
python core-backup.py
Try changing response encoding to UTF-8:
response.encoding = 'UTF-8'
print(response.json())
Related
This is the code I wrote to get user balance from BingX API.
I think I do everything correct but it doesn't work properly.
import urllib.request
import json
import base64
import hmac
import time
APIURL = "https://open-api.bingx.com"
APIKEY = "MyApiKey"
SECRETKEY = "MySecretKey"
def genSignature(paramsStr):
return hmac.new(SECRETKEY.encode("utf-8"),
paramsStr.encode("utf-8"), digestmod="sha256").digest()
def post(url, body):
req = urllib.request.Request(url, headers={
'User-Agent': 'Mozilla/5.0',
'X-BX-APIKEY': APIKEY,
}, method="GET")
return urllib.request.urlopen(req).read()
def getBalance():
paramsMap = {
"timestamp": int(time.time()*1000)
}
paramsStr = "&".join(["%s=%s" % (k, paramsMap[k]) for k in paramsMap])
paramsStr += "&signature=" + genSignature(paramsStr).hex()
url = "%s/openApi/swap/v2/user/balance?%s" % (APIURL, paramsStr)
return post(url, paramsStr)
def main():
print(getBalance())
if __name__ == "__main__":
main()
But when I run it I get this:
b'{"code":100001,"msg":"","success":false,"timestamp":1675069039381}'
This is the doc link
The response from the API is indicating that the request was unsuccessful and returned a code of 100001 with a success value of false. This means that there was some sort of signature authentication error in the request that was made.
The 100001 error code means that the signature authentication has failed. The signature is used to verify the authenticity of the request, so if the signature is incorrect, the request will fail.
There are a few things that could be causing the signature to fail:
Incorrect calculation of the signature: Make sure the code for generating the signature is correct and follows the requirements of the BingX API.
Incorrect encoding: Make sure the signature is properly encoded before being added to the request as a query parameter.
Incorrect secret key: Make sure the secret key used to generate the signature is correct and up-to-date.
Incorrect time stamp: Make sure the time stamp included in the request is correct and in the correct format.
You should carefully review the code and the API documentation to ensure that the signature is being generated correctly and that all required information is included in the request. If the issue persists, you may also want to reach out to the BingX API support team for additional assistance.
import requests
# Replace YOUR_API_KEY with your actual Binance API key
headers = {'X-MBX-APIKEY': 'YOUR_API_KEY'}
# Make a GET request to the Binance account endpoint
response = requests.get('https://api.binance.com/api/v3/account', headers=headers)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Get the user's available balance for the specified asset
asset_balance = [balance for balance in data['balances'] if balance['asset'] == 'BTC'][0]['free']
print('User balance:', asset_balance)
else:
# Handle the error
print('Error:', response.text)
I have a yaml file : file.yaml structured as follows :
index:
- uid: "uid"
name: "name"
headline: "headline"
overview: "overview"
features: "features"
instructions: "instructions"
callback_url: "https://some-url.com/params"
edit_url: "https://edit-url/params"
uninstall_hook: "https://uninstall-url/params"
svg:
screenshot1:
screenshot2:
screenshot3:
I have to upload those informations to an api endpoint by performing a PUT request. I managed to do it first using the register.py following script that I just run python register.py:
import json
import requests
from pathlib import Path
import base64
import yaml
BASE_URL = "https://url.com" # API Host
FILE_FOLDER = Path.cwd() # Current working directory
if __name__ == "__main__":
public_key = <public_key>
private_key = <private_key>
auth_key = "{}:{}".format(public_key, private_key).encode("utf-8")
encodedKey = base64.b64encode(auth_key).decode("utf-8")
headers = {"Authorization": f"Basic {encodedKey}", "Content-type": "application/json"}
def update_app_info():
infos_file = FILE_FOLDER / "file.yaml"
with open(infos_file) as infos_file_data:
yamlcontent = yaml.safe_load(infos_file_data) # Parse file.yaml and produce a dictionary of it
file_infos = yamlcontent["index"][0] # retrieve actual configuration informations
response = requests.put(
f"{BASE_URL}/path/to/api_endpoint/{public_key}", data=json.dumps(file_infos), headers=headers
)
print(response)
print(response.json())
update_app_info()
That gives a 202 success response.
As you may observe, I tried to get content of the yaml file as a dicitonary and send that in data. I proceeded that way regarding format of data at GET https://url.com/path/to/api_endpoint (mock example for illustration...) . Having the dictionary file_infos seemed more appropriate and gets me a success response. Sending directly the file itself or 'infos_file_data' gave me some errors I got over with the above script.
The issue is when I update svg, screenshot1, screenshot2 & screenshot3 so that file.yaml is now :
index:
- uid: "uid"
name: "name"
headline: "headline"
overview: "overview"
features: "features"
instructions: "instructions"
callback_url: "https://some-url.com/params"
edit_url: "https://edit-url/params"
uninstall_hook: "https://uninstall-url/params"
svg: "icon.svg"
screenshot1: "screenshot1.png"
screenshot2: "screenshot2.png"
screenshot3: "screenshot3.png"
That gives now :
<Response [400]>
{'error': {'message': {'svg': ['The submitted data was not a file. Check the encoding type on the form.'], 'screenshot1': ['The submitted data was not a file. Check the encoding type on the form.'], 'screenshot2': ['The submitted data was not a file. Check the encoding type on the form.'], 'screenshot3': ['The submitted data was not a file. Check the encoding type on the form.']}, 'code': 400}}
I've done multiple searches (1 , 2 , 3 , 4 , 5...) but their application and few other errors, eventually get me to this :
import base64
import json
from pathlib import Path
import requests
import yaml
from requests_toolbelt.multipart.encoder import MultipartEncoder
BASE_URL = "https://url.com" # API Host
FILE_FOLDER = Path.cwd() # Current working directory
if __name__ == "__main__":
public_key = <public_key>
private_key = <private_key>
auth_key = "{}:{}".format(public_key, private_key).encode("utf-8")
encodedKey = base64.b64encode(auth_key).decode("utf-8")
def update_app_info():
infos_file = FILE_FOLDER / "file.yaml"
with open(infos_file) as infos_file_data:
yamlcontent = yaml.safe_load(infos_file_data) # Parse file.yaml and produce a dictionary of it
file_infos = yamlcontent["index"][0] # retrieve actual configuration informations
m = MultipartEncoder(fields=file_infos)
#print(m.content_type)
headers = {
"Authorization": f"Basic {encodedKey}",
"Content-Type": m.content_type,
}
response = requests.put(
f"{BASE_URL}/path/to/api_endpoint/{public_key}",
data=json.dumps(file_infos),
headers=headers
)
print(response)
print(response.json())
update_app_info()
That is also giving me the 202 success response but the file svg, screenshot1, screenshot2 & screenshot3 fields are not updated.
I'll share more informations where needed. Your help is very welcome.
I've got additional resources that helped.
As I was trying to solve my issue, I found this. It happens I didn't wrote files part as it should, plus I was having data as a JSON string. That causes a ValueError: Data must not be a string. error. This was useful to get it fixed.
Now, for what it's worth, here's the working script :
import base64
from pathlib import Path
import requests
import yaml
BASE_URL = "https://url.com" # API Host
FILE_FOLDER = Path.cwd() # Current working directory
if __name__ == "__main__":
public_key = <public_key>
private_key = <private_key>
auth_key = "{}:{}".format(public_key, private_key).encode("utf-8")
encodedKey = base64.b64encode(auth_key).decode("utf-8")
def update_app_info():
infos_file = FILE_FOLDER / "file.yaml"
with open(infos_file) as infos_file_data:
yamlcontent = yaml.safe_load(infos_file_data) # Parse file.yaml and produce a dictionary of it
if "index" in yamlcontent:
file_infos = yamlcontent["index"][0] # retrieve actual configuration informations
headers = {
"Authorization": f"Basic {encodedKey}",
}
files = {
"svg": open("icon.svg", "rb"),
"screenshot1": open("screenshot1.png", "rb"),
"screenshot2": open("screenshot2.png", "rb"),
"screenshot3": open("screenshot3.png", "rb"),
}
response = requests.put(
f"{BASE_URL}/path/to/api_endpoint/{public_key}", data=file_infos, files=files, headers=headers
)
print("\n", response)
print("\n", response.headers)
print("\n", response.json())
update_app_info()
First thank you for your time. I'm trying to do an insert using a Rest-API POST, I'm working with Python. Among my messages I have special characters that I want to keep in the destination, which by the way returns an error for them since by default the messages are in UTF-8, but I want them in "ISO-8859-1".
For this I have created the line: headers["Charset"] = "ISO-8859-1" . Python does not give me an error but I continue with the same problem.
The error is:
400 Client Error: Bad Request for url: https://api.example.com/
Here is my code:
import requests
from requests.structures import CaseInsensitiveDict
url = 'https://api.example.com/'
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer "
headers["Content-Type"] = "application/json"
headers["Charset"] = "ISO-8859-1"
collet_x = df_spark.collect()
for row in collet_x:
#insert
resp = requests.post(url, headers=headers, data=row['JSON'])
v_respuesta = resp.text
print(resp.status_code)
print(v_respuesta)
How else can I change the encoding?
From already thank you very much.
Regards
I'm trying to get data about a stream via the twitch api, the first request for the oauth2 token works perfectly, but then as soon as I make the first request I get this error 401 Client Error: Unauthorized for url: https://api.twitch.tv/helix/users?login=im_marcotv&. What I understand is that there is an error in my token submission, but I don't understand what I did wrong, this is the complete code:
import requests
import os
import json
from dotenv import load_dotenv
load_dotenv()
CLIENTID = os.getenv("CLIENTID")
CLIENTSID = os.getenv("CLIENTSID")
sCLIENTID = str(CLIENTID)
sCLIENTSID = str(CLIENTSID)
if __name__ == "__main__":
print("print1")
request_token_url = f'https://id.twitch.tv/oauth2/token?
client_id=&client_secret=&grant_type=client_credentials'
response = requests.post(request_token_url)
response.raise_for_status()
print(response.json())
token = json.loads(response.text)["access_token"]
print(f"Token: {token}")
header = {"Client-ID": "", f"Authorization": "Bearer {token}"}
response = requests.get("https://api.twitch.tv/helix/users?login=im_marcotv&", headers=header)
response.raise_for_status() #line that raise the error
print(response.json())
data = json.loads(response.text)["data"]
if data:
streamer = data[0]
user_name = streamer["user_name"]
game_name = streamer["game_name"]
viewer_count = streamer["viewer_count"]
output = f"{user_name} is online on {game_name} con {viewer_count} visualizzazioni"
print(output)
else:
#print(f"{name} is offline")
pass
The line getting the token was also giving the same error, but I fixed it by stopping using variables to hold the client id and secret id. In all the places where there should be the ids I removed them, but in the actual code they are present and correct
I have a web server and can run python on it, like this:
import os
from urllib.parse import parse_qsl
def main():
thestring = os.environ["QUERY_STRING"]
parameter_dict = dict(parse_qsl(thestring))
print(parameter_dict)
print("Content-Type: text/plain")
print("")
main()
If I hit is like this: http://127.0.0.1/web.py?hello=world
I'll get a nice little hash:
{'hello': 'world'}
That works just fine for my purposes. Now what I'm trying to do is make this webserver accept json input.
I'm using this code to 'throw' json at the URL
body = {
"username":"user1",
"folder":"folder1"
}
req = urllib.request.Request("http://127.0.0.1/web.py")
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
content = json.loads(response.read().decode("utf-8"))
print(content)
But what do I need to do in my top section of code to have web.py 'accept' the json and be able to use it? Ideally just put the json into a dict. I bet this is just something really simple and I'm just missing a basic command. Thank you in advance!