The code
#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>" print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM books ORDER BY pub_date DESC LIMIT 10”)
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
How can you solve the problem?
[edit] after the first answer
test.cgi is executable (I run $ chmod +x test.cgi)
I use Apache.
I have this in .bashrc export PATH=${PATH}:~/bin
Python module MySQLdb is installed.
The code does not have smart quotes.
[edit] after the second answer
you're getting that error because you
haven't installed the MySQLdb module
that Python needs to talk to a MySQL
database
I installed MySQLdb to my system. The module works, since I can import them.
However, I still get the same error whet I go to the www.[mysite].com/test.cgi.
[edit]
I am not sure about the questions
Are the connect() parameters correct? Is MySQL running on localhost
at the default port?
I run MySQL on my server. Is the question about the connect() parameters relevant here?
Is the SELECT statement correct?
You mean whether I have my SQL statements such as SELECT statement correct?
I have not used any SQL queries yet.
Do I need them here?
Any number of issues can cause the error you are seeing:
Is test.cgi executable (chmod 755) on the server?
Is the directory in which you placed test.cgi designated as a ScriptAlias location or have the ExecCGI option enabled (or equivalent if you're not using Apache)?
Is python in the system PATH or in the PATH in the Web server's startup environment?
Is the MySQLdb Python library installed?
Are the connect() parameters correct? Is MySQL running on localhost at the default port?
Is the SELECT statement correct?
If you're sure that python is found (test using the simplest possible script or by logging into the Web server if you can and typing which python) then you can get much better debug output by adding the following to the top of your script just below the shebang:
import cgitb
cgitb.enable()
More details: http://docs.python.org/library/cgitb.html
Additionally, if you have shell access to the Web server, try running python and just typing:
>>> import MySQLdb
If the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation.
EDIT: Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server.
I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with " and '. Do you have any more luck with the following? Can you run it from a terminal just by typing python test.cgi?
#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
The error in http://dpaste.com/8866/ is occurring because you are using "curly quotes" instead of standard ASCII quotation marks.
You'll want to replace the “ and ” with ". Just use find and replace in your text editor.
Make sure you're saving the file with correct line endings. i.e. LF only on unix, or CR/LF for Windows. I just recently had the exact same problem...
Related
I'm very new to Python, seriously, painful newb question here.
Uploaded domainname.com/test.py to server containing nothing but:
#output data
import sqlite3
connection = sqlite3.connect("company.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee")
print("fetchall:")
result = cursor.fetchall()
for r in result:
print(r)
cursor.execute("SELECT * FROM employee")
print("\nfetch one:")
res = cursor.fetchone()
print(res)
it's literally just displaying output
#output data
import sqlite3
connection = sqlite3.connect("company.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM employee")
print("fetchall:")
result = cursor.fetchall()
for r in result:
print(r)
cursor.execute("SELECT * FROM employee")
print("\nfetch one:")
res = cursor.fetchone()
print(res)
in PHP or ASP I would use <% %> - feel like I'm missing something obvious here. Obviously in PHP I would easily output this to the screen - I can't seem to find a basic explanation of how to do this in python.
I tried domainname.com/test.cgi moved it to various folders etc still nothing.
I'm using a Linux Operating System. It recommends PYTHON 2.7 which is enabled. I'm just using Sublime Text editor. I do have latest Python 3.8 on my machine presumably this simple code should still work.
What am I missing to enable Python to run server side.
Add the shebang, with the Python interpreter location, at the first line of the file, for example:
#!/usr/local/bin/python
print('Ciao')
# Other code....
The interpreter could be installed in different locations depending on the server configuration, in my example was /usr/local/bin/python
The reason this script did not execute was that the shared hosting server (once activated as python was not installed by default) took a while to switch over to supporting (installing) python scripts, during this period the script did not appear run properly. The script above now runs.
what's wrong with this line of code?
whenever I run it it shows syntax error 'mysql' check the corresponding server version.
import mysql.connector
import builtins
import importlib.util
import os
v=os.getcwd()
loc=""
for i in v:
if i == "\\":
loc += "/"
else:
loc += i
print(loc)
def crt():
m=mysql.connector.connect(host="localhost",user="root",passwd="****")
mc=m.cursor()
mc.execute("create database if not exists mydb")
crt()
m=mysql.connector.connect(host="localhost",user="root",passwd="****",database="mydb")
mc=m.cursor()
mc.execute("source "+loc+"/mydb.sql;")
normally for mysql when I apply the following code it works.
use mydb;
source C:\Users\15fri\OneDrive\Desktop\s3ts\mydb.sql
as for the for loop section in the previous code I converted the backslashes to forward slashes since some time the location in the code even works with forward slashes..
Your problem is probably that source is not an SQL command and that it's only available from within the mySQL CLI.
Try reading the script file and passing its contents as a string to mc.execute()
In response to your comment CrazY JoN, I'm no Python programmer but I was thinking of something like this:
sql_script_file = open("source "+loc+"/mydb.sql;",'r')
sql_script = sql_script_file.read()
sql_commands = sql_script.split(";") # assuming the commands in the script have to be executed one at a time
for cmd in sql_commands:
mc.execute(cmd)
I am trying to connect to a DB2 JDBC database thru Python with providing the SSLClientKeystoredb.
This is how I have been trying to connect to the DB:
import ibm_db
arg1 = "DRIVER={IBM DB2 ODBC DRIVER};" + "DATABASE=databasename;HOSTNAME=" + "server" + ";PORT=" + "111111" + ";PROTOCOL=TCPIP;UID=" + "userId" + ";PWD=" + "password" + ";SECURITY=ssl" + ";SSLClientKeystoredb=" + "C:/Users/path/db2_ssl_keydb.kdb" + ";SSLClientKeystash=" + "C:/Users/path/db2_ssl_keydb.sth"
conn=ibm_db.connect(arg1, "", "")
I keep getting this error:
SQLCODE=-1109M][CLI Driver] SQL1109N The command was not processed because the database manager failed to load the following DLL: "GSKit Error: 202". SQLSTATE=42724
I installed both GSKit8 Crypt and GSKit SSL 64-bit. Any help would be appreciated !
On Db2-client workstations, you can avoid installing/configuring the GSK8 as a separate component, and still have encrypted SSL connections to Db2-LUW servers.
Note that you might need GSK8 on client-workstations for other reasons (other non-Db2 applications), but that is a separate matter.
On MS-Windows, there are two ways to avoid having to install GSK8 for Db2 SSL connections, but in this answer I mention one way.
Technically this feature became available at V10.5 fixpack 5 Db2-clients, but there were some bugs so I suggest to avoid that fixpack and start with fixpack 8 or higher. This functionality also works in V11.1 Db2-clients.
If you have the server-certificate in ARM format, then you can use the SSLSERVERCERTIFICATE and SECURITY keywords in the connection-string to connect with SSL from Python (or from any tool that uses the Db2 CLI libraries).
With this approach you don't need a keystore and stash to be manually created, and you don't need SSLClientKeystoredb etc in the connection string.
You still need to add appropriate security for the ARM file both at rest and during distribution.
This approach may be easier to manage, and example connection is below:
try:
arg1="DATABASE=whatever;HOSTNAME=whatever;PORT=50443;UID=whavever;PWD=whatever;SSLServerCertificate=/path_to/db2server_instance.arm;SECURITY=ssl;"
conn = ibm_db.connect(arg1,"","")
except:
logging.error('Error: Failed to connect to database: %s', ibm_db.conn_errormsg())
sys.exit(1)
Don't know if it helps, but when I launched the gitBash / command prompt via "run as administrator" it worked for me. After I used the
conn=ibm_db.connect("Database=****DB; Hostname=***.***.***.COM; PORT=****; Security=ssl; SSLClientKeystoredb=c:/keystore/ibmca.kdb; SSLClientKeystash=c:/keystore/ibmca.sth;UID= ; PWD= ;",'','')
"202 - GSK_KEYRING_OPEN_ERROR
Unable to open the key file or the Microsoft Certificate Store. Either the path was specified incorrectly or the file permissions did not allow the file to be opened, or the file format is incorrect."
The arg1 passed to ibm.db is badly formatted and you are missing a semi-colon after you assign your SSLClientKeystash. Try following this: IBM Support
The issue was solved by switching to python 2.7.9, and changing the path of the SSL to "C:\SSL" for the certificates. Not sure if changing the path helped but just wanted to mention that for future reference.
I am new to superset.
Going to Sources > Databases for a new connection to my athena.
I have downloaded JDBC driver and writing following connection line:
awsathena+jdbc://AKIAJ2PKWTZYAPBYKRMQ:xxxxxxxxxxxxxxx#athena.us-east-1.amazonaws.com:443/default?s3_staging_dir='s3://aws-athena-query-results-831083831535-us-east-1/' as SQLAlchemy URI. First parameter being access key and 2nd being secret key(Modified a bit for privacy)
I am getting the error:
ERROR: {"error": "Connection failed!\n\nThe error message returned was:\nCan't load plugin: sqlalchemy.dialects:awsathena.jdbc"}
I really wish to explore the open source visualisation using superset on my databases.
As per Superset documentation, you need to escape/encode at least the s3_staging_dir, i.e.,
s3://... -> s3%3A//...
Have you followed that step?
If you are sure you have done pip install "PyAthenaJDBC>1.0.9" in the same python environment as you start your superset. Try restarting Superset in the same environment.
In my case problem was with the special characters in the aws_secret_key and s3_staging_dir. I solved it by putting the output of quote_plus methods into the URI. No quotes were required.
from urllib.parse import quote_plus
secretkey = quote_plus(aws_secret_access_key)
loc = quote_plus(s3_staging_dir)
Further, make sure the schema_name (i.e. database name) already exists in the s3 path. Hope it helps!
I'm very new to Python and MySQL and this is my first Stack question. So, apologies in advance if I'm missing something obvious. But, I really did try to research this before asking.
I'm trying to learn the basics of Python, MySQL, and CGI scripting. To that end, I've been reading tutorials at http://www.tutorialspoint.com/python/python_cgi_programming.htm and http://www.tutorialspoint.com/python/python_database_access.htm, among others.
I'm trying to have a CURL GET or Python Requests GET call a Python CGI script on a test server. That Python CGI script would then perform a Read action on a local MySQL database and return the results to CURL or to Python Requests.
The Python CGI script I've created outputs the MySQL Read data perfectly to the terminal on the remote test server. But, it won't return that output to the CURL or to the Python Requests that triggered the CGI script.
This is the Python CGI script I've cobbled together:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fetch data"
# disconnect from server
db.close()
My guess is that I need to somehow pass the data from the SQL query back to Python or back to the requesting process through some sort of Return or Output statement. But, all my best efforts to research this have not helped. Can anyone point me in the right direction? Many thanks for any help!
Marc :-)
First, as per the CGI tutorial you link, you need to output the content type you are working with:
print "Content-type: text/plain\r\n\r\n",
If you don't at least have the newlines in there, HTTP clients will think your content is supposed to be part of the headers and get confused, they will probably assume the document you asked for is empty.
Next, you need a CGI server. Python comes with one. Place your script in a subdirectory called cgi-bin and run this command (from the parent directory):
python -m CGIHTTPServer
The url to call will look something like this:
curl http://localhost:8000/cgi-bin/cgitest.py