I'm running the following code with web.py to get mysql data and print it out on a webpage. For some reason, when I query the webpage, I get just the word "None". Any idea what the problem is? There is some data in the MySQL database, the credentials are valid, and the code is running without any errors.
import web
import MySQLdb
import json
import collections
db=MySQLdb.connect(user="someuser",
passwd="somepass",db="somedatabase")
urls = (
'/', 'index',
'/test', 'test'
)
class index:
def GET(self):
c=db.cursor()
c.execute("""
SELECT email, password
FROM users
""")
rows = c.fetchall()
I think your code fragment may be either incomplete or misformatted, but assuming it is not, the GET method has no return statement, which means that any invocation would return None, which in turn would be rendered as the string
"None"
Related
We have created a API which takes data from PowerBI and provides output in JSON format.
We have made some modifications to the original pyadomd code, and it runs without errors. However, it is not displaying the PowerBI data in JSON format as it should.
Original code: https://pypi.org/project/pyadomd/.
from sys import path
path.append('\\Program Files\\Microsoft.NET\\ADOMD.NET\\160')
from pyadomd import Pyadomd
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/Alpino')
def get_data():
conn_str = 'Provider=MSOLAP;User ID=Alexw#dettol.com;Data Source=powerbi://api.powerbi.com/v1.0/myorg/Power BI Model [Test];initial catalog=PBI_Model_20230121;Password=Alexw#2023;Persist Security Info=True;Impersonation Level=Impersonate;'
query = """EVALUATE Project"""
with Pyadomd(conn_str) as conn:
with conn.cursor().execute(query) as cur:
data = cur.fetchall()
print(data)
return jsonify(data)
if __name__ == '__main__':
app.run()
For better understanding of Pyadomd library, see also the link above.
Output:
No PowerBI Data are fetched & Return with 404 Error:
I think app.route is unable to fetch the file path.
When we have used default code it generates Authentication error & after modification now it is not showing output in JSON format. When we mention alpino in url file path it provides 404 error.
I have made changes into code & issue has been resolved. Please find below code.
Python Code :
from sys import path
path.append('\\Program Files\\Microsoft.NET\\ADOMD.NET\\160')
from pyadomd import Pyadomd
from flask import Flask, jsonify
# Create a Flask app
app = Flask(__name__)
# Define an API endpoint
#app.route('/alpino')
def alpino():
# Connect to Power BI and execute query
conn_str = 'Provider=MSOLAP;User ID=Alexw#dettol.com;Data Source=powerbi://api.powerbi.com/v1.0/myorg/Power BI Model [Test];initial catalog=PBI_Model_20230121;Password=Alexw#2023;Persist Security Info=True;Impersonation Level=Impersonate;'
query = 'EVALUATE ROW("ProjectRowCount",COUNTROWS(Project) )'
with Pyadomd(conn_str) as conn:
with conn.cursor().execute(query) as cur:
data = cur.fetchall()
column_names = [column[0] for column in cur.description]
# Convert query result to a list of dictionaries
result = [dict(zip(column_names, row)) for row in data]
# Convert the list of dictionaries to a JSON string
json_result = jsonify(result)
return json_result
if __name__ == '__main__':
app.run()
Output :
[Json Output]
: https://i.stack.imgur.com/YYbzy.png
Query Explanation :
This code defines a Flask API endpoint that connects to a Power BI data source and executes a query. Here's a step-by-step breakdown of the code:
The first two lines import the necessary libraries: sys.path and pyadomd for working with the Power BI data source, and flask for building the API endpoint.
from sys import path
path.append('\Program Files\Microsoft.NET\ADOMD.NET\160')
from pyadomd import Pyadomd
from flask import Flask, jsonify
The next line creates a Flask app instance with Flask(name).
app = Flask(name)
The #app.route('/alpino') decorator is used to define the API endpoint. In this case, the endpoint URL is http:///alpino.
#app.route('/alpino')
The def alpino(): function defines the behavior of the API endpoint. It first sets up a connection to the Power BI data source with the given connection string and then executes a query using the Pyadomd library.
def alpino():
The cur.fetchall() method retrieves all the data returned by the query.
with Pyadomd(conn_str) as conn:
with conn.cursor().execute(query) as cur:
data = cur.fetchall()
The column_names variable is set to the list of column names returned by cur.description.
column_names = [column[0] for column in cur.description]
The result variable is set to a list of dictionaries, where each dictionary represents a row in the query result. The zip() and dict() functions are used to map the column names to the row values.
result = [dict(zip(column_names, row)) for row in data]
The jsonify() function is used to convert the result variable to a JSON string.
json_result = jsonify(result)
Finally, the function returns the JSON response using return json_result.
return json_result
In summary, this code sets up a Flask API endpoint that connects to a Power BI data source and returns the result of a query in JSON format. It uses the pyadomd library to connect to the data source, and the flask library to define the API endpoint and return the JSON response.
#Stay Healthy #Stay Safe
Hope your query got resolved. If you have any query, Feel free to contact us.
|| Jay Hind Jay Bharat ||
i'm beginner in sqlalchemy, i want to reflect my table in database to object, but always return invalid password, even though the password is correct. I dont understand why this happend. When i try to inspect they return my table name, so my password, connection string or on create_engine is correct.
when my database have no password is fine i can reflect it to Object, that's so weird.
but why when i reflect database with password it's error, always return "Not a valid password" ??,
My MS. Access Tbl 1
My MS. Access Tbl 2
Error in Reflect but My Table name is returned
This is my Code
because I was curious I also made a test select data, and it turned out to be successful in retrieving the data
it's returned my data and success created connection
when i add some code for testing
I think all it's correct but why cannot reflect??, Please Help.
My Reference connection_string
My Reference SqlAlchemy Automap Reflect
I have just released sqlalchemy-access version 1.1.1 to address this issue. Note that as described in Getting Connected if you want to use a pass-through ODBC connection string with an encrypted database you need to supply the password in two places:
driver = "{Microsoft Access Driver (*.mdb, *.accdb)}"
db_path = r"C:\Users\Public\test\sqlalchemy-access\gord_test.accdb"
pwd = "tiger"
connection_string = (
f"DRIVER={driver};"
f"DBQ={db_path};"
f"PWD={pwd};"
f"ExtendedAnsiSQL=1;"
)
connection_uri = (
f"access+pyodbc://admin:{pwd}#/"
f"?odbc_connect={urllib.parse.quote_plus(connection_string)}"
)
engine = sa.create_engine(connection_uri)
I am looking for your help because i am getting this error on Python Flask:
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Autoevaluacion', 'RT_Funcionarios', 'Reporteadores', 'Reporteadores_Gerentes', '' at line 1")
I am inserting data from Angular in my MySQL DB with the help of Flask, i am trying to insert the fields name, email, role and foros, this last one is filled with the elements of an array so when i tried to save the data, that error is shown.
this is my python code
#app.route('/insertarUsuario', methods = ["POST"])
def insertar_usuario():
conection = pymysql.connect('localhost', 'root','root', 'users')
data = request.json
print(data)
print(data['foros'])
cursor = conection.cursor()
sql_query ="INSERT INTO administrador_usuarios(nombre, email, rol, foros) VALUES ('" + str(data["nombre"]) + "','"+ str(data["email"])+"','"+str(data["rol"])+"', '"+ str(data["foros"])+"')"
cursor.execute(sql_query)
conection.commit()
response = "OK"
print("respuesta:",response)
return jsonify(response)
I would like to highlight 2 things:
1-. that array that will fill the field foros, it comes from the number of foros you select through checkboxes, so if i just check one, the register is saved but if i checked more than one, it crashes.
2-. i found out that if i replace
(data["foros"])
for
str("autoevaluacion" + "rt_funcionario")
it works so i think maybe it about how do i receive the array.
Can you help me please?. I am kinda new on Flask
I have a mysql database in which 'user' table having f_name,l_name,password email(pk) by which session is created and table 'friendgroup' having fg_name(pk), email((pk),users.email(FK)) and table 'member' having email(pk,user.email(fk)), owner_email(pk,friendgroup.email(fk)), fg_name(pk,friendgroup.fg_name(fk)), and a python flask file below.
After login account, I wish to add a friend in chat. I tried to fix it from session['email']
def add_friend():
user = session['email']
friendgroups = _get_own_friendgroups(user) return
render_template('addFriend.html', friendgroups=friendgroups)
def _get_own_friendgroups(user):
cursor = mysql.connection.cursor()
#find all friendgroups that the user owns
find_owned_friendgroups = 'SELECT fg_name, description FROM friendgroup WHERE owner_email = %s ORDER BY fg_name ASC'
cursor.execute(find_owned_friendgroups, (user))
owned_friendgroups = cursor.fetchall()
cursor.close()
return owned_friendgroups
I expect output will be an open window and actively use of add friend when needed but showing error:
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
A common error in python is to use (bar) instead of (bar,) the former not being a tuple.
Try with:
cursor.execute(find_owned_friendgroups, (user,))
I've been trying to get SPARQLWrapper to insert a simple triple into GraphDB with no success. I have no trouble with select queries. Here's Python test code that fails:
db = sparqlw.SPARQLWrapper(endpoint)
query = '''
INSERT {<http://example.com/123456789876> a owl:Thing .}
WHERE {}
'''
db.setQuery(query)
db.method = sparqlw.POST
db.setReturnFormat(sparqlw.JSON)
db.queryType= sparqlw.INSERT
result = db.query()
It returns these errors:
"urllib.error.HTTPError: HTTP Error 400: Bad Request"
and
"SPARQLWrapper.SPARQLExceptions.QueryBadFormed: QueryBadFormed: a bad
request has been sent to the endpoint, probably the sparql query is bad
formed."
Response:
b'Missing parameter: query'
I've looked everywhere and tried everything suggested and can't get it to work. Grateful for any good leads.
See my added comment on validation of the query. The suggestion that the question is a duplicate and already answered is not applicable.
GraphDB exposes Sesame-style endpoint URLs.
Here below a screenshot of GraphDB 8.3 Workbench help page (I'm using Free Edition).
The following Python code works for me (repositoryID is wikidata):
from SPARQLWrapper import SPARQLWrapper, BASIC
db = SPARQLWrapper("http://localhost:7200/repositories/wikidata/statements")
query = '''
INSERT {<http://example.com/123456789879> a owl:Thing .}
WHERE {}
'''
db.setHTTPAuth(BASIC)
db.setCredentials('login', 'password')
db.setQuery(query)
db.method = "POST"
db.setReturnFormat('json')
db.queryType = "INSERT"
result = db.query()