Saving rdflib.Graph into a dictionary - python

I would like to save an rdflib.Graph into the session dictionary within my Flask application as I need to access it from other route functions. The code is as follows.
from rdflib import Graph
from flask import Flask, session
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config["allowed_file_extensions"] = ["ttl"]
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.secret_key = os.urandom(24)
class API:
def __init__(self):
app.run(host="127.0.0.1", port="5000", threaded=True, debug=True)
#app.route("/")
def validate_RDF():
# saving graph to session
graph = Graph().parse("valid_mapping.ttl", format="ttl")
session["graph"] = graph
return "testing"
if __name__ == "__main__":
# start api
API()
Which outputs the following.
TypeError: Object of type 'Graph' is not JSON serializable
Any advice would be greatly appreciated.

As a rdf graph can be large, it is anyway not a good idea to try to store it in the session in my opinion. You should rather use some kind of triple store to manage your rdf information (like a web site is using a database to store information. See for instance RDFlib 'on disk' store for a store on your web server disk, or for production you would even use a triple store hosted elsewhere.

Related

Using Reserved Ngrok Domain with Flask-Ngrok

I have written a simple API using Flask. It works when run on my local machine and when testing using Ngrok. The issue I have is that Ngrok changes the IP each time the API is run.
I have a paid Ngrok plan and have reserved a domain but I can't work out how to point the API to the domain.
I can't see anything in the docs but it seems fairly basic functionality so I'm at a bit of a loss.
What am I missing?
Here's my code (go easy, I'm a beginner):
from flask import *
from flask_ngrok import run_with_ngrok
import json, time
app = Flask(__name__)
run_with_ngrok(app)
#app.route('/', methods=['GET'])
def test_data():
json_address_details = open('address_details.json')
address_details = json.load(address_bet_details)
print(address_details)
json_address_details.close()
json_dump = json.dumps(address_details)
return json_dump
if __name__ == '__main__':
app.run()

Flask: Storing Socket-Connection variables without Cookies

I need to have 'variables and activity associated with each client' without using cookies. How and where can i store this variables? I am pretty new to flask and servers.
For now, I thought of using a python dictionary and storing sessionID-variable pairs like shown below.
I have a feeling that this is a stupid idea, but I can not think of an alternative :/.
Hope, you can help me.
import flask
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
enter code heresocketio = SocketIO(app)
cache = {}
#app.route('/')
def index():
return send_from_directory('static', "index.html")
#socketio.on('savePseudonym')
def sendKeepAlive():
cache[(request.sid,'pseudonym')]= pseudonym
cache[(request.sid,'time')]= time
if __name__ == "__main__":
socketio.run(app, debug=True)
You can use session, in more or less the same way you use it with Flask routes.
from flask import session
#socketio.on('savePseudonym')
def sendKeepAlive():
session['pseudonym'] = pseudonym
session['time'] = time
The only thing to keep in mind is that because Socket.IO sessions are not based on cookies, any changes you make to the session in a Socket.IO handler will not appear on the Flask session cookie. If you need to share the session between Flask routes and Socket.IO event handlers, then you can use a server-side session with the Flask-Session extension.

Initializing Firestore-Admin in Flask app

I have a Flask app that uses Cloud Firestore for some functions. I am using the Firestore-Admin library which works fine, but I assume I placed its initializing code wrongly. My knowledge about how Flask apps work is limited so I just simply added the following code to my app.py:
cred = credentials.Certificate('key.json')
fault_app = firebase_admin.initialize_app(cred)
db = firestore.client()
While the code works, my question is that is it a proper solution to initialize the Firestore? Does this solution fits into the lifecycle of a Flask app? I already tried to init the Firestore directly from the methods that use it, but that made server errors because the amount of initializations.
Below Example Might Help you :
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from flask import Flask
app = Flask(__name__)
cred = credentials.Certificate("key.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
#app.route('/getdata')
def user_data():
#getting the docs
users_ref = db.collection('Demo')
docs = users_ref.get()
for doc in docs:
print('{} => {}'.format(doc.id, doc.to_dict()))
return "Recorded Printed"
if __name__ == '__main__':
app.run()
Looks reasonable to me. It's the same approach taken in this tutorial.

No response from a Flask application using Apache server

I have created a flask application and am hosting it on a Ubuntu server. I know that my apache config is correct since I am able serve the example flask application. However, this one seems to be giving me trouble. The code is below:
from flask import Flask, render_template, request, url_for
import pickle
import engine
import config
# Initialize the Flask application
app = Flask(__name__)
model = pickle.load(open(config.MODEL_PATH, "rb"))
collection = engine.Collection(config.DATABASE_PATH)
search_engine = engine.SearchEngine(model, collection)
#app.route('/')
def form():
return render_template('index.html')
#app.route('/search/', methods=['POST'])
def search():
query = request.form['query']
results = search_engine.query(query)
return render_template('form_action.html', query=query, results=results)
#app.route('/retrieve/<int:item_number>', methods=['GET'])
def retrieve(item_number):
item = engine.Product(item_number, collection.open_document(str(item_number)))
return render_template('document.html', item=item)
if __name__ == '__main__':
app.run()
When running the file directly through the python interpreter, it works fine and I can access. However, when starting through apache and wsgi, I get no response from the server. It just hangs when making a request and nothing is available on the logs.
I suspect that my issue may have something to do with the three objects I initialize at the beginning of the program. Perhaps it gets stuck running those?
Update: I have tried commenting out certain parts of the code to see what is causing it to stall. Tracing it out to the engine module, importing NearestNeighbors seems to be causing the issue.
import sqlite3
import config
from sklearn.neighbors import NearestNeighbors
from preprocessor import preprocess_document
from collections import namedtuple

Trouble Hosting flask app on pythonanywhere

I am a first time user of pythonanywhere
I first started by doing a git clone of my code from github through the bash console. I did not use a virtual environment. My WSGI app was invoked in my app.py file. Also, my code uses sqlalchemy to interact with my database.
Basically, the flask app was like a custom api that returned JSON for GET and POST requests and I am having trouble viewing the JSON output. I am not sure what exactly I am doing wrong or missing.
Code in app.py file:
#!flask/bin/python
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Base, Quote
from flask import request
from flask import abort
import json
#connect to database
engine = create_engine("sqlite:///quotes.db")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
app = Flask(__name__)
#app.route("/trumptext/api/quotes", methods=["GET"])
def get_quotes():
quoteList = session.query(Quote).all()
result = []
for q in quoteList:
my_dict = {}
my_dict["id"] = q.id
my_dict["quote"] = q.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8')
#app.route("/trumptext/api/quotes", methods=["POST"])
def add_quote():
if not request.json or not "quote" in request.json:
abort(400)
new_quote = request.json["quote"]
q = Quote(quote=new_quote)
session.add(q)
session.commit()
quoteList = session.query(Quote).all()
last = quoteList[-1]
result = []
my_dict = {}
my_dict["id"] = last.id
my_dict["quote"] = last.quote
result.append(my_dict)
return json.dumps(result,ensure_ascii=False).encode('utf8'), 201
if __name__ == "__main__":
app.run()
Also, code in /var/www/nnelson_pythonanywhere_com_wsgi.py:
import os
import sys
path = '/home/nnelson/trumptextapi'
if path not in sys.path:
sys.path.append(path)
from app import app as application
If I enter something like :
http://nnelson.pythonanywhere.com/trumptext/api/quotes (to perform a GET request)
It should ideally return all the quotes stored in the quotes.db database in JSON format, however all I get it output that looks like this: [] I tested my code on localhost using the curl tool and it works just fine. I am having trouble hosting it though
Any help is appreciated.
You're using a relative path to your database, so it's probably looking at a database that you don't expect. Use a full path to the database or make it relative to the path of your app.py file so that you know where it's getting the database from.

Categories

Resources