How do I fetch data from API in Flask? - python

I'm trying to set up a Flask API Server from which I can data from local database via an ongoing HTTP Request to another database.
In the local code, I run a thread that is running and updating the local DB every 1 minute.
app = Flask(__name__)
cached_event_log = None
#app.route('/event_log', methods=['GET'])
def get_event_log():
if cached_event_log != None and .get_latest_event_time == cached_event_log[-1]:
return jsonify(cached_event_log)
#MAKE CONNECTION TO DB AND GET THE DATA
return jsonify(event_log)
if(__name__ == '__main__'):
app.run(Debug=True)
I'm struggling to find a "standard" way to set up A request.
Any opinion would be highly appreciated- Thank you,

You could set up a cron job to run a script at a specified interval
Or use something like Advanced Python Scheduler
https://apscheduler.readthedocs.io/en/3.0/
Advanced Python Scheduler support in Flask
https://github.com/viniciuschiele/flask-apscheduler

Related

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.

Trading view alerts to trigger market order through python and Oanda's API

I'm trying to trigger a python module (market order for Oanda) using web hooks(from trading view).
Similar to this
1) https://www.youtube.com/watch?v=88kRDKvAWMY&feature=youtu.be
and this
2)https://github.com/Robswc/tradingview-webhooks-bot
But my broker is Oanda so I'm using python to place the trade. This link has more information.
https://github.com/hootnot/oanda-api-v20
The method is web hook->ngrok->python. When a web hook is sent, the ngrok (while script is also running) shows a 500 internal service error and that the server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
This is what my script says when its running (see picture);
First says some stuff related the market order then;
running script picture
One thing I noticed is that after Debug it doesn't say Running on... (so maybe my flask is not active?
Here is the python script;
from flask import Flask
import market_orders
# Create Flask object called app.
app = Flask(__name__)
# Create root to easily let us know its on/working.
#app.route('/')
def root():
return 'online'
#app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
# Parse the string data from tradingview into a python dict
print(market_orders.myfucn())
else:
print('do nothing')
if __name__ == '__main__':
app.run()
Let me know if there is any other information that would be helpful.
Thanks for your help.
I fixed it!!!! Google FTW
The first thing I learned was how to make my module a FLASK server. I followed these websites to figure this out;
This link helped me set up the flask file in a virtual environment. I also moved my Oanda modules to this new folder. And opened the ngrok app while in this folder via the command window. I also ran the module from within the command window using flask run.
https://topherpedersen.blog/2019/12/28/how-to-setup-a-new-flask-app-on-a-mac/
This link showed me how to set the FLASK_APP and the FLASK_ENV
Flask not displaying http address when I run it
Then I fixed the internal service error by adding return 'okay' after print(do nothing) in my script. This I learned from;
Flask Value error view function did not return a response

Creating an API to execute a python script

I have a python script app.py in my local server (path=Users/soubhik.b/Desktop) that generates a report and mails it to certain receivers. Instead of scheduling this script on my localhost, i want to create an API which can be accessed by the receivers such that they would get the mail if they hit the API with say a certain id.
With the below code i can create an API to display a certain text. But, what do i modify to run the script through this?
Also if i want to place the script in a server instead of localhost, how do i configure the same?
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return ("hello world")
if __name__ == '__main__':
app.run(debug=True)
Python Version is 2.7
A good way to do this would be to put the script into a function, then import that function in your Flask API file and run it using that. For hosting on a web server you can use Python Anywhere if you are a beginner else heroku is also a good option.
If you are tying to achieve something using Python-Flask API than you can have a close look at this documentations and proceed further https://www.flaskapi.org/, http://flask.pocoo.org/docs/1.0/api/
Apart from these here are few basic examples and references you can refer for a quickstart :
1-https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
2- https://flask-restful.readthedocs.io/en/latest/
3- https://realpython.com/flask-connexion-rest-api/
You could do something like this
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class ExecuteScript:
def printScript:
return "Hello World"
api.add_resource(ExecuteScript, '/printScript')
if __name__ == '__main__':
app.run(debug=True)

Sharing global information across requests to flask endpoints on heroku

I have a flask application with a single endpoint, like this (simplified below):
#app.route('/classify', methods=['POST'])
def classify():
p = g.model_loader.get_model()
json = request.get_json()
text = json['text']
return p.classify(text)
def main():
model_loader = ResourceLoader()
with app.app_context():
g.model_loader = model_loader
app.run()
if __name__ == '__main__':
main()
The application needs to load a machine learning model into memory once, in the main method, and then use that model to classify text that is being sent via POST to a flask endpoint. I've tried to do this using an application context, which works locally, but doesn't work on heroku. My understanding currently is that this is because the application context isn't shared across workers. How can I give the classify endpoint access to the model loader?
EDIT: I didn't word the initial question correctly. Each worker should run main() and should thus have access to model_loader in its own application context. However, when I run this on heroku, I get AttributeError: '_AppCtxGlobals' object has no attribute 'model_loader'. Does the application context differ on heroku?
You can't load it into memory once, because Heroku workers might be on completely different machines. You need to run this code in every worker, or store the data somewhere it can be read by any process.

Updating the webpage using Flask based on MySQL database.

I have a webpage (built using HTML & jQuery) which displays the data from a MySQL database. I am using Flask to connect HTML with my database. However, my database gets updated every 15 minutes (using a separate Python Script). Currently, I stop the flask server, update the database and restart the Flask to update the webpage. My question is the following:
Is there a way to update the MySQL database in the background without having to stop the flask server? I read about concepts of AJAX and CRON, however i am not able to understand how to use them with flask asynchronously.
Note: I am a newbie in web applications and this is my first project which involves connecting client side and server side. Any help will be appreciated.
Thanks
You are most likely doing something like this:
from flask import Flask, render_template
from yourMySqlLibrary import connect_to_mysql
conn = connect_to_mysql()
# This is only executed when you start the script
data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")
app = Flask(__name__)
#app.route("/")
def view_data():
return render_template("view_data.html", data=data)
if __name__ == "__main__":
app.run()
If that is the case, then your solution is simply to move your connection and query calls into your controller so that the database is re-queried every time you hit the page:
#app.route("/")
def view_data():
# Removed from above and placed here
# The connection is made to the database for each request
conn = connect_to_mysql()
# This is only executed on every request
data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")
return render_template("view_data.html", data=data)
This way, your view will update when your data does - and you won't have to restart the server just to pick up changes to your data.

Categories

Resources