Python cgi does not work with requests - python

#!/usr/bin/python3
import cgi
import cgitb
import json
import requests
print("Content-type: application/json\n")
print("making request...")
searchrequest = requests.get("https://google.com")
print(json.dumps(searchrequest.text))
following code works when executed from terminal, but when executed as cgi script, the output will only be "making request...", the program basically stopped running after request.get() had been executed.
Any ideas? Its so weird.
EDIT-1
Problem resolved, it has nothing to do with the library itself. I figured out the problem after adding cgitb.enable() which enables the error report and tells me what the actual problem is.

Related

How Do I Make an API Call from Python v2.7.13 When the Requests Module Isn't Available

Good-day Folks,
I am writing a small Python script that will be used on a Ubiquiti EdgeRouter 12P to make an API Call, using Digest Authentication, against another router for some JSON data. This is my first attempt at writing a Python script and I have been able to do this using the Requests module, but only in a Python v3.x.y environment. As I was writing my script, I discovered that the Python version on the EdgeRouter is v2.7.13 and the Requests module isn't installed/loaded.
I have attempted to do a pip install requests but it fails with an invalid syntax error message. So with my limited knowledge, I can't figure out what my options are now. Googled around a bit and saw references to using UrlLib or UrlLib2 - but I'm struggling with figuring out how to use either to make my API Call using Digest Authentication.
I would very much like to stick to the Requests module, as it appears to be the simplest and cleanest approach. Below is a snippet of my code, any help would be really appreciated, thanks.
PS. My script is not yet finished, as I'm still learning how to parse the response data received.
HERE'S MY SCRIPT
#PYTHON MODULE IMPORTS
import sys #Import the Python Sys module - used later to detect the Python version
PythonVersion = sys.version_info.major #Needed to put this global variable up here, so I can use it early
import json #Import the JSON module - used to print the API Call response content in JSON format
if PythonVersion == 3: #Import the REQUESTS and HTTPDigestAuth modules - used to make API Calls if we detect Python version 3
import requests
from requests.auth import HTTPDigestAuth
if PythonVersion == 2: #Import the UrlLib module - used to make API Calls if we detect Python version 2
import urllib
#GLOBAL VARIABLES
NodeSerial = '1234'
NodeIP = '192.168.1.100'
BasePath = 'api/v0.1'
apiURL = f"http://{NodeIP}/{BasePath}/MagiNodes"
#Define the credentials to use
Username='admin'
Passwd='mypassword'
#MAIN ROUTINE
print("This is a test script")
if PythonVersion == 2:
print("Python Version 2 detected")
elif PythonVersion == 3:
print("Python Version 3 detected")
print(f"Now querying MagiLink-{NodeSerial}...")
Query1 = requests.get(f"{apiURL}/{NodeSerial}", auth=HTTPDigestAuth(Username, Passwd)) #Using an F string
pretty_Query1 = json.dumps(Query1.json(), indent=3) #Pretty printing the response content
print(pretty_Query1)

Why does my .exe generated by PyInstaller not start?

I generated an executable file with PyInstaller, but when I want to launch the application the console window shows me, that it couldn't find a directory or file. I checked the location and the folder "_MEI55762" is indeed not present.
Did anyone have this issue before?
Below the part of the code, where I think the error should be located. I think it has something to do with the imports of the "jsonrpclcient" package. I didnĀ“t post the full code with the all the GUI lines, since I think it will not help. If I am wrong please let me know.
import os
import sys
import requests
import json
import pyvisa
import time
from datetime import datetime
import threading
import signal
from jsonrpcclient import *
from jsonrpcclient.clients.http_client import HTTPClient
from jsonrpcclient.requests import Request
from tkinter import *
from tkinter import ttk
import traceback
print("-----------------------------------------")
print(" Q-Center V0.1 ")
print("-----------------------------------------")
port = ":8080"
rm = pyvisa.ResourceManager()
def listArticles():
for attempt in range (3): #Will be executed 3 times in case an error occurs
print('List Articles:')
try: #First try this
client = HTTPClient("http://" + ipEntry.get() + port)
response = client.send(Request("list_articles"), timeout=5)
print(response.data.result)
print('Success!')
except: #If an error occurs, call the print function and let the user know
print('An error occured!')
rebootPeacock()
else: #If no error occurs, stop trying
break
else: #If no attempt was successful, print that all 3 attempts failed. ONLY EXCUTED WHEN THE LOOP DOES'T BREAK.
print('All 3 attempts failed!')
answer = response.data.result
pkReply.insert(END, answer)
pkReply.insert(END, '\n\n')
The solution is to tell PyInstaller to add the "response-schema.json" file which is located at "C:\Users\pfra\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\jsonrpcclient".
So the command should look like:
pyinstaller --add-file "C:\Users\pfra\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\jsonrpcclient.response.schema.json;."

Python 3 script crash on lru_cache

I have raspberry pi acting as MFRC522 card reader. So far I have a script which worked on python 2.7, but when I tried to move to python 3, bizarre thing happened.
I used updated library for it: https://github.com/pimylifeup/MFRC522-python and adjusted my script accordingly
I installed pip3 and spidev
Here is where strange thing happens. If I run demo script from repo above in new folder it works, cool.
But if I put my previous script in the same folder it returns error as below. And after that if I try again to run demo script, same error occurs.
Moving both script to different folder, has the same effect. I can run demo only before my script. Doing that after, is impossible.
Error:
File "/usr/lib/python3.7/re.py", line 297, in <module>
#functools.lru_cache(_MAXCACHE)
AttributeError: module 'functools' has no attribute 'lru_cache'
My script:
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import time
import requests
import signal
import sys
import os
# some functions non related to MFRC522
reader = SimpleMFRC522()
while continue_reading:
try:
id, text = reader.read()
#print id
#print "---"
ver = query_server(id)
if ver == 1:
open_relay(5)
else:
#do something
finally:
time.sleep(0.5)
It's like folder is somehow tainted after firing my script, what am I missing?

How can I call another python script, in a python script, based on a variable in a config file?

I have below py script to download the files from artifactory.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import tarfile
import urllib
from urllib import urlretrieve
import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('/vivek/release.conf')
code_version = Config.get('main', 'app_version')
os.chdir('/tmp/')
arti_st_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/abc.ear/{0}/abc.ear-{0}.tar.gz'.format(code_version)
arti_st_name='abc.ear-{0}.tar.gz'.format(code_version)
arti_sl_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/def.ear/{0}/def.ear-{0}.tar.gz'.format(code_version)
arti_sl_name='def.ear-{0}.tar.gz'.format(code_version)
urllib.urlretrieve(arti_st_url, arti_st_name)
urllib.urlretrieve(arti_sl_url, arti_sl_name)
oneEAR = 'abc.ear-{0}.tar.gz'.format(code_version)
twoEAR = 'def.ear-{0}.tar.gz'.format(code_version)
tar = tarfile.open(oneEAR)
tar.extractall()
tar.close()
tar1 = tarfile.open(twoEAR)
tar1.extractall()
tar1.close()
os.remove(oneEAR)
os.remove(twoEAR)
This script works perfectly, thanks to stackoverflow.
Here's the next question. There's a variable "protocol" in release.conf. If it's equal to "localcopy", there's an existing py script that does something. If the "protocol" is equal to "artifactory",
above script should be called and executed. How can I achieve it?
Note: I am a beginner in Python, but my tasks are not. So, please help me out guys.
You could simply use:
import os
os.system("script_path")
to execute the script file. But there should be a line called shebang in the very top of that script file, you want to execute. If your python interpreter would be in /usr/bin/python this would be:
#!/usr/bin/python
Assuming you are a Linux user.
In Windows shebang isn't supported. It determines what program to use running *.py file itself.
//Edit:
To call that two scripts depending on a property config value you could just make another script called for example runthis.py which contains instruction like:
protocol = Config.get('main', 'protocol')
if protocol == 'localcopy':
os.system('path_to_localcopy_script)
if protocol == 'antifactory':
os.system('path_to_other_script')
Dont forgot to import needed modules in that new script.
Then you just run script you just made.
That is one way to do this.
If you dont want to create additional script, then put that code you wrote in a function, like:
def main():
...
Your code
...
And on the very bottom of your script file write:
if __name__ = '__main__':
protocol = Config.get('main', 'app_version')
if protocol == 'localcopy':
main()
if protocol == 'antifactory':
os.system('path_to_other_script')
if __name__ = '__main__' would execute only if you run that script by yourself (not by call from an other sctipt for example)

Python : no JSON object could be decoded

I am trying to run this app:
https://github.com/bmjr/guhTrends
I have python 2.7.x running the following script at command line. I reckon it was written using python3.x. What is deprecated in the code below?
import urllib
import json
import matplotlib.pyplot as plt
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
dataDates = json.loads(dates.read().decode())
the error:
Traceback (most recent call last):
File "DataMining.py", line 6, in <module>
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
AttributeError: 'module' object has no attribute 'request'
That script won't work under python2 as urllib of python2 has no request module.
Use urllib2.urlopen instead of urllib.request if you want start running that script under python2 .
To get python script work on bith (python2 and python3) use six module which is Python 2 and 3 Compatibility Library.
from six.moves import urllib
import json
import matplotlib.pyplot as plt
dates = urllib.request.urlopen('http://charts.spotify.com/api/tracks/most_streamed/global/weekly/')
dataDates = json.loads(dates.read().decode())
You're requesting a resource that is not currently available (I'm seeing a 504). Since this could potentially happen any time you request a remote service, always check the status code on the response; it's not that your code is necessarily wrong, in this case it's that you're assuming the response is valid JSON without checking whether the request was successful.
Check the urllib documentation to see how to do this (or, preferably, follow the recommendation at the top of that page and use the requests package instead).

Categories

Resources