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
Related
I am working on a website where we have different levels and sublevels. Is it possible to generate the sublevels on the fly based on level clicked.
I am working with it in a flask application.
Note : Website is connected to google analytics and has multiple levels and is impossible to do it manually.
str.split('/') should do the trick, when used with Flask's request. Request's path holds the part after www.example.com/
Simple example. Note the empty first result in the returned list
from flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main():
return 'Hello'
#app.route('/path/to/wherever')
def example():
for p in request.path.split('/'):
print(p)
return str(request.path.split('/'))
if __name__ == "__main__":
app.run()
lets say I have this code
s =int(input("Input a number "))
x = s+5
print(x)
how do I run it on EC2 and then use flask to get the output using POST so I can use it on a front end ?
I want to make a webpage where a user can input s and then the backend which is an index.py file that communicates with AWS EC2 (using flask) to run the python code above and then return the value x to the front end
flask app sample code
#!/usr/bin/python
from flask import Flask, request, jsonify
from index import some_fun
app = Flask(_name_)
#app.route('/foo', methods=['POST'])
def foo():
data = request.form.to_dict()
function_response = some_fun(data['form_field'])
print(function_response)
return jsonify(data)
if __name__ == "__main__":
app.run()
You python script, index.py from where you want call some_function
def some_fun(x): return x + 5
here i have considered post request is of multipart/form-data.
if you are making post request with application/json
then
data = request.json
I started learning Flask framework recently and made a short program to understand request/response cycle in flask.
My problem is that last method called calc doesn't work.
I send request as:
http://127.0.0.1/math/calculate/7/6
and I get error:
"Not Found:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
Below is my flask app code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "<h1>Hello, World!</h1>"
#app.route('/user/<name>')
def user(name):
return '<h1>Hello, {0}!</h1>'.format(name)
#app.route('/math/calculate/<string:var1>/<int:var2>')
def calc(var1, var2):
return '<h1>Result: {0}!</h1>'.format(int(var1)+int(var2))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)
To access request arguments as described in your comment you can use the request library:
from flask import request
#app.route('/math/calculate/')
def calc():
var1 = request.args.get('var1',1,type=int)
var2 = request.args.get('var2',1,type=int)
return '<h1>Result: %s</h1>' % str(var1+var2)
The documentation for this method is documented here:
http://flask.pocoo.org/docs/1.0/api/#flask.Request.args
the prototype of the get method for extracting the value of keys from request.args is:
get(key, default=none, type=none)
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)
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'