Neo4j Python bolt driver: how to convert the result to Json? - python

I am using the bolt driver(1.0.1) with python. How can I convert the result into a Json so that I can return it to through a flask app?
That is I need to convert datatype, "neo4j.v1.types.Record" to "json".
I tried this
from flask import Flask
from neo4j.v1 import GraphDatabase, basic_auth
import json
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j","neo4j"))
session = driver.session()
app = Flask(__name__)
#app.route('/hello/<prop>')
def hello_name(prop):
result = session.run("MATCH ...") #this works perfectly fine and the data is captured in result
session.close()
for record in result:
return json.loads(record)
This throws an error :- TypeError: the JSON object must be str, not 'Record'

The neo4j driver gives the result in a generator.(Record Type) You cannot do json.load as it is not a json serialized string.
What you can do :
for record in result:
print result[0]
See the format of the result and take the elements you like.
For further understanding on how to parse neo4j records:
http://neo4j.com/docs/api/python-driver/current/session.html

Related

Using Python Pyadomd Library to get PowerBI Data into Json Format

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 ||

Neo4j python driver | AttributeError: 'Session' object has no attribute 'execute_read'

In the Neo4j Python code, I have an issue while query from Neo4j DB, with getting below error:
AttributeError: 'Session' object has no attribute 'execute_read'
I want to convert the results of cypher queries into a JSON format.I am using the neo4j python library to connect the graph DB.
Here is my current code:
cypherQuery="MATCH (n:BusinessApplication) RETURN n"
#Run cypher query
with driver.session() as session:
results = session.execute_read(lambda tx: tx.run(cypherQuery).data())
driver.close()
The session.execute_read function was introduced in a more recent version of the Neo4j Python driver (5.0) so you may see that error because you're using a previous version of the Neo4j Python driver that does not support that function.
You could upgrade to a more recent version 5.0+ of the Neo4j Python driver to use the execute_read syntax or use the read_transaction function instead:
def get_business_apps(tx):
results = tx.run("MATCH (n:BusinessApplication) RETURN n")
for record in results:
# do something with each record
print(record['n'])
with driver.session() as session:
session.read_transaction(get_business_apps)
driver.close()

How do I return SQL table using Python API with Provided Parameter?

I am trying to call an API to serve data from a MSSQL database. If I input only the endpoint without parameter, it successfully shows the error of missing param. When I insert param with wrong/unavailable id, it will show result as {"data": []}. However, if I insert correct parameter into the ID, the error 500 occur. May I know where should I adjust so that I will be able to get the data from the table. Below is my codes for the endpoints.
from flask_restful import Resource
from flask import request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import app_config
class Test(Resource):
def get(self):
id = request.args.get("id", None)
UGengine = create_engine(f'{app_config.SQL_SERVER_STRING}')
UGSession = scoped_session(sessionmaker(bind=UGengine))
s = UGSession()
if id:
query_data = s.execute(f"SELECT * FROM [DBName].[TABLE]"
f"WHERE [ID] = '{id}'")
else:
return {"message": "Missing required query param: id"}, 400
query_result = query_data.fetchall()
return {"data": query_result}
in App.Py
api.add_resource(Test, "/test")
Are you sure about your Database structure?
Does your Database have really the Name "DBName" and your Table has the Name "TABLE"?
[DBName].[TABLE]
Br

Python MySQLdb Query Returns "None"

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"

how to fetch specific collection from mongodb in django

I have clouded the mongodb collection for my project in Amazon server.
I am new to mongodb queries. When I connect and look in 'robomongo' tool, I can see that there two databases A and B. I want to access the one collection named 'wl_c' under B in view function in django and convert to JSON data.
I do not know how to do even though I tried,
from pymongo import Connection
server = '000.00.000.00'
port = 00000
conn = Connection(server,port)
def mongo(request):
mdb = conn.events.polls_post.find({})
data = json.dumps(mdb)
return HttpResponse(data, mimetype="application/json")
got
Type error mdb is not json serializable
find({}) returns cursor. You need to get the items. Either cast to list or iterate over the result.
Something like:
mdb = conn.events.polls_post.find({})
mdb_list = list(mdb)
json.dumps(mdb_list)
Look here

Categories