Passing variables aquired using flask as input to script - python

I have a python setup where one method continuously returns the IDs of scanned RFID chips. Now I cut the cord and have the scanner hooked up to a wifi microcontroller (ESP8266). Every time a chip is scanned a GET request is issued containing the chip's ID.
I put the flask part in a simple script. I don't need anything returned to the ESP8266. I would like to just have a class or functions that just return the collected value. I can print the value to stdout where it appears also with flask's log output but this doesn't really help. How do I pass uid to a different script, what am I missing?
The script in question:
from flask import Flask
app = Flask(__name__)
#app.route('/urlpath/<uid>')
def rfiduid(uid):
print uid
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=False)

You would just need to import your other and call it directly from within the route.
from flask import Flask
# A module which contains the stuff you're trying to do
from myothermodule import processRFID
app = Flask(__name__)
#app.route('/urlpath/<uid>')
def rfiduid(uid):
# Pass the UID to your other module here
processRFID(uid)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=False)
If your other code is literally a script (that accepts input arguments from the command line) I would recommend modifying it so that it contains a function that you can call from the flask app. Otherwise, you will need to use an os.system call or something to execute the other script with arguments. This is highly discouraged since you are passing un-sanitized user input (via the url) to your system.
#app.route('/urlpath/<uid>')
def rfiduid(uid):
os.system(' '.join(['script.py', uid]))
This could be exploited if a UID were passed as '1 && really_bad_system_command'

Related

Flask API not accessible outside of local network despite using Host='0.0.0.0'

hi i have made a really basic example here to attempt to make this easy to understand, i have a simple flask api that returns a single string, it is fully accessible using localhost, but i want to be able to access it from outside of the local network. i have created a firewall rule that allows TCP traffic in and out on port 5000, but despite this, it does not work. this is currently running in a pycharm community edition IDE, but i have ran it from command line aswell with the same results.
Why can i not access it using http://[IP]:5000/test
my end goal is to be able to access it from any identity given using Tor service using Torrequests module, but to get that far i need to be able to access it externally in the first place
from flask import Flask, request
from flask_restful import Resource, Api
import logging
app = Flask(__name__)
api = Api(app)
class Test(Resource):
def post(self):
return "worked"
def get(self):
return "worked"
api.add_resource(Test, '/test', methods=['GET', 'POST'])
if __name__ == "__main__":
app.run(debug=False ,host='0.0.0.0', port=5000)

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

Exposing an endpoint for a python program

I want to expose an endpoint for a simple python program that takes in an input and manipulates it to return an output which would be the easiest approach for it.
example can be any simple python function such as:
def func(string):
string= len (string)
return tuple(int(string[i:string/2],6) for i in range (0,6,3)
It doesn't necessarily needs to be a web service. This is a microservice that can then be containerized
I need to be able to send in the i/p and receive an o/p in response communicating through the endpoint
Assuming that by input and output, you mean normal data types like int, string, etc. and by end point you mean web services: You can read about Flask . Flask allows you to create web services in python.
from flask import Flask
app = Flask(__name__)
#app.route('/end_point', methods=['GET'])
def hello():
if request.method == 'GET':
input = request.args.get('input', None)
return func(input)
def func(string): string= len (string) return tuple(int(string[i:string/2],6) for i in range (0,6,3)
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
Now you can access your end point on http:\\localhost:8000\end_point?input=your_input

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)

Requests not able call multiple routes in same Flask application

I am not able to successfully use Python Requests to call a second route in the same application using Flask. I know that its best practice to call the function directly, but I need it to call using the URL using requests. For example:
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!" # This works
#app.route("/myrequest")
def myrequest():
#r = requests.get('http://www.stackoverflow.com', timeout=5).text # This works, but is external
#r = hello() # This works, but need requests to work
r = requests.get('http://127.0.0.1:5000/', timeout=5).text # This does NOT work - requests.exceptions.Timeout
return r
if __name__ == "__main__":
app.run(debug=True, port=5000)
Your code assumes that your app can handle multiple requests at once: the initial request, plus the request that is generated while the initial is being handled.
If you are running the development server like app.run(), it runs in a single thread by default; therefore, it can only handle one request at a time.
Use app.run(threaded=True) to enable multiple threads in the development server.
As of Flask 1.0 the development server is threaded by default.

Categories

Resources