I am looking for a way to make the parameters I would send through a json file global, so they can be easily used from differente functions inside the code. At the moment I can reproduce this by sending these parameters inside the http request and not from a json.
example code:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class ApiPage(Resource):
def calculation(self, a, b):
total = a + b
return total
def get(self, a, b):
total1 = self.calculation(a, b) + 10
return {'total': total1}
api.add_resource(ApiPage, '/<int:a>/<int:b>')
if __name__ == '__main__':
app.run(debug=True, port=8070)
http that works:
http://127.0.0.1:8070/120/80
Json file I am looking to use:
{"a":120, "b":80}
Related
In the Flask script below, I want to use the results of the endpoint '/three' in my endpoint '/five'.
The endpoint for '/three' works fine, however when I try the endpoint '/five', I get the error: TypeError: 'Response' object is not subscriptable.
How do I correctly use the output of '/three' to compute '/five'?
from flask import Flask, url_for, redirect
app = Flask(__name__)
#app.route('/three')
def three():
return {'message':3}
#app.route('/five')
def five():
old_message = redirect(url_for('three'))['message'] # expect to return 3
new_message = {'message':old_message + 2 } # 3+2 = 5
return new_message # expecting {'message':5}
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
if you want to trigger the three method via http request, you could use requests package, then JSON-parse it, manipulate and return to the client:
from flask import jsonify
import requests
import json
...
...
...
#app.route('/three')
def three():
return {'message':3}
#app.route('/five')
def five():
http_req = requests.get('http://localhost:8000/three')
my_three_json = json.loads(http_req.text)
my_three_json["message"] += 2
return jsonify(my_three_json)
I'm setting up an API REST with flask-restful. I have not found any documentation nor examples of how an internal call among endpoints would be done. Said otherway, I want to consume one of the endpoints from inside the implementation of other endpoint.
I could treat it like an usual external call to another API but I feel like I would be commiting a crime against good practices somehow
from flask import Flask, request
from flask_restplus import Api, Resource
app = Flask(__name__)
api = Api(app, version='1.0', title='FooTitle',
description='FooDescription', )
ns_conf = api.namespace('FooName', description='FooDescription')
# Endpoint 1
#ns_conf.route('/endpoint1')
class MyResource(Resource):
def get(self):
return 'Hello '
# Endpoint 2
#ns_conf.route('/endpoint2')
#api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
def get(self):
# Transfer request parameters to variables:
your_name= request.args.get('your_name')
# I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
hello = call_endpoint_1()
return hello + str(your_name)
What is the correct way to implement 'call_endpoint_1()'?
Quite simply: factor out the common part into a plain function and call it from both endpoints:
def say_hello():
return "Hello "
#ns_conf.route('/endpoint1')
class MyResource(Resource):
def get(self):
return say_hello()
# Endpoint 2
#ns_conf.route('/endpoint2')
#api.doc(params={'your_name': 'Your name'})
class greeting(Resource):
def get(self):
# Transfer request parameters to variables:
your_name= request.args.get('your_name')
# I WOULD LIKE TO GET THE OUTPUT OF ENDPOINT 1 here:
hello = say_hello()
return hello + str(your_name)
I am trying to send an Array of doubles periodically from a python service to another.
As a beginner in python I have read a lot about Flask and requests. And here is a simple example code. I just want to learn the syntax. Can anybody tell me what is wrong with it.
Server1: send an array via flask
from flask import Flask
app = Flask(__name__)
a=[]
for i in range(10):
a.append(i)
#app.route('/')
def hello_world():
return '{}'.format(a)
if __name__ == '__main__':
app.run(debug=True)
Server 2: get the array and perform some mathematical operations
import requests
r = requests.get('https://127.0.0.1:5000')
y = r[1] + r[2]
print(y)
My main question is: how can I transfer doubles and integers instead of strings via Flask?
It's better to use JSON or other data format for data exchange instead of strings.
Example with json:
# SEND
from flask import jsonify
...
#app.route('/')
def hello_world():
d = {"my_numbers": list(range(10))} # create data structure
return jsonify(d) # respond with JSON reporesentation of data
...
# GET
import requests
r = requests.get('https://127.0.0.1:5000')
if r.status_code == 200: # request was successful
numbers_array = r.json()["my_numbers"] # get [0, 1, 2, ...] from response
print(numbers_array[1] + numbers_array[2]) # perform math ops
else: # server is down or wrong request
print('error getting data from server:', r.status_code, r.text)
I have a Python Flask application that uses the requests library. I am trying to implement OpenTracing in the application. A simplified version is:
from flask_opentracing import FlaskTracer
from flask import Flask
from jaeger_client import Config
from opentracing_instrumentation.client_hooks import install_all_patches
from os import getenv
import requests
JAEGER_HOST = getenv('JAEGER_HOST', 'localhost')
def initialise_tracer():
config = Config(
config={
'local_agent': {
'reporting_host': 'jaeger'
}
},
service_name='opentracing_test',
validate=True
)
return config.initialize_tracer()
app = Flask(__name__)
tracer = FlaskTracer(initialise_tracer, trace_all_requests=True, app=app)
install_all_patches()
#app.route('/foo')
def foo():
r = requests.get('http://localhost/bar')
return 'foo : ' + r.text
#app.route('/bar')
def bar():
return 'bar'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
All endpoints are traced because of giving trace_all_requests to FlaskTracer. All requests made with the requests library are traced because of install_all_patches() from opentracing_instrumentation.
My '/foo' endpoint makes a request to '/bar'. When I access the '/foo' endpoint and view the traces, I can see two separate traces: One containing just '/foo', and a second that contains both the requests GET and the call to '/bar'. I would have expected the spans to propagate through the entire process and therefore I should see a single trace with '/foo' -> GET -> '/bar'.
Do I need to manually set the headers on each of my requests to pass the span? It looks like that is exactly what the requests monkey patch should do...
In my Flask application, I want to expose a URI like this:
http://<base_uri>/some_string
and I wish to handle requests to it differently depending on whether some_string is an integer or not.
With Sinatra I can achieve that via "passing" as shown below:
get '/:some_string' do
if is_integer(:some_string)
'Your URI contains an integer'
else
pass # This will pass the request on the the method below which can handle it
end
get '/*' do
'Your URI contains some string'
end
Here the call pass in the first route lets the second route process the request if :some_string is not an integer.
I couldn't find any equivalent functionality in Flask. Can someone please suggest a solution in Flask?
Type conversion in url routes can do this for you:
from flask import Flask
import unittest
app = Flask(__name__)
app.debug = True
#app.route('/<int:thing>')
def num(thing):
return 'INT'
#app.route('/<thing>')
def string(thing):
return 'STR'
class TestDispatch(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_int(self):
resp = self.client.get('/10')
self.assertEqual("INT", resp.data)
def test_str(self):
resp = self.client.get('/hello')
self.assertEqual("STR", resp.data)
if __name__ == '__main__':
unittest.main()