Python flask: return values multiple times - python

I ran my code on Jupyter Notebook and I wanted to return different values on the web while running the function. However, it only returned one value. I also tried yield, but it had an error on the web.
from werkzeug.wrappers import Request, Response
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
list = [0,0,0]
for i in range(10):
list.append(i)
return str(list)
if __name__ == "__main__":
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)
Output:
[0,0,0,0]
Expected Output:
[0,0,0,0]
then change to:
[0,0,0,0,1]
then go on until it stops at:
[0,0,0,0,1,2,3,4,5,6,7,8,9]

Your indent is a little off on the return of the list. This is returning it on the first loop. Corrected Code is below:
from werkzeug.wrappers import Request, Response
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
list = [0,0,0]
for i in range(10):
list.append(i)
return str(list)
if __name__ == "__main__":
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)

Related

Python Code on my XAMPP Website won´t work

from flask import Flask, render_template, request
import random
import datetime
app = Flask(__name__)
# List to store the submitted URLs
urls = []
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
url = request.form['url']
# Add the URL to the list and return a success message
urls.append(url)
return "URL submitted successfully!"
#app.route('/stream')
def stream():
# Select a random URL from the last 20 days
now = datetime.datetime.now()
twenty_days_ago = now - datetime.timedelta(days=20)
recent_urls = [url for url in urls if url.submission_time > twenty_days_ago]
current_song_url = random.choice(recent_urls)
return render_template('stream.html', url=current_song_url)
if __name__ == '__main__':
app.run(debug=True)
I want to use this Code for my XAMPP Website (Html/php mostly used) but it only shows the code. So I watched some tutorials with config stuff and all that but then there is an internal server error. What should I do?
I tried to config Apache (httpd.conf) and installed everything (Python, Flask etc.)

How to call microservice-2 from microservice-1 using python?

How to call my microservice-2 from microservice-1. So our result looks like this:-
Result :- {“message”: “vivek”} --> {“message”: “keviv”, “random”: 3.89}
command to access microservice-1:-
curl http://127.0.0.1:5000/reverse_random/vivek
microservice-1
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/reverse_reandom/<string:string>', methods=['GET'])
def reverse(string):
string = string[::-1]
return jsonify({'message': string })
if __name__ == '__main__':
app.run(debug = True)
microservice-2
import random
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/', methods=['GET'])
def myRandom():
r1 = random.uniform(0, 10)
return jsonify({'message': r1 })
if __name__ == '__main__':
app.run(debug=True)
you'll need to issue a GET request to service 2 in order to get the random number, I suggest to use requests for this, like
r = requests.get('url-for-service-2:port/')
data = r.json()
random_num = data['message']
keep in mind to check the data object for message key, or using .get() or equivalent
Run microservice-2 on a different port. Send request using Python standard or 3rd party library from microservice-1
to microservice-2 upon request to microservice-1.
Below is the example of using Python3 standard library only:
m1.py:
from flask import Flask, jsonify
import urllib
import json
app = Flask(__name__)
#app.route('/reverse_random/<string:string>', methods=['GET'])
def reverse(string):
content = urllib.request.urlopen('http://127.0.0.1:5001').read().decode('utf-8')
print('response from m2: ', content)
string = string[::-1]
return jsonify({'message': string, 'random' : json.loads(content)['message']})
if __name__ == '__main__':
app.run(debug = True)
m2.py:
import random
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/', methods=['GET'])
def myRandom():
r1 = random.uniform(0, 10)
return jsonify({'message': r1 })
if __name__ == '__main__':
app.run(debug=True, port=5001) # running m2 on a different port than default 5000
Run the m1: python3 m1.py
Run the m2 in a different shell: python3 m2.py
Send request to m1: curl http://127.0.0.1:5000/reverse_random/vivek
The result is:
{
"message": "keviv",
"random": 4.138115905045612
}
Observe the log of m1 and of m2 to make sure m2 was invoked.
To connect between services you can use background tasks such as celery and ramq or use nsq and nats

random number generator using python

I am creating a microservice using Flask, that needs to give me a random number.
Unfortunately I am getting this error:
AttributeError: 'function' object has no attribute 'uniform'
import random
from flask import Flask
app: Flask = Flask(__name__)
#app.route('/', methods=['GET'])
def random():
r1 = random.uniform(0, 10)
return r1
if __name__ == '__main__':
app.run(debug=True)
new to microservice and python.
It is because you redefined random. You can either change the function name or give alias to imported random library.
Method 1:
Change the function name you defined.
import random
from flask import Flask
app: Flask = Flask(__name__)
#app.route('/', methods=['GET'])
def myRandom(): //Changed here
r1 = random.uniform(0, 10)
return r1
if __name__ == '__main__':
app.run(debug=True)
Method 2
Import random using alias.
import random as r //Changed here
from flask import Flask
app: Flask = Flask(__name__)
#app.route('/', methods=['GET'])
def random():
r1 = r.uniform(0, 10)
return r1
if __name__ == '__main__':
app.run(debug=True)

Printing any value to web server with Flask

My question is very simple, when you run this code :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
You will see Hello World! on 127.0.0.1:5000
But I' m trying to change like this, I took "Internal Server Error".
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
a= 5+10
return a
if __name__ == '__main__':
app.run()
Code Source: http://flask.pocoo.org/docs/quickstart/#a-minimal-application
Your hello_world method should return a str or file-like object, but in this case you're returning an int. Just cast:
#app.route('/')
def hello_world():
a = 5 + 10
return str(a)
If you are still learning Flask, it would be a good idea to enable debug mode.
app.debug = True
app.run()
Or pass it as a parameter to run:
app.run(debug=True)
This way, you'll see more than just a 500 error.

Running background Celery task in Flask

Problem has been updated to include progress made
I have the following code and my celery tasks kick off fine, I just don't know where I should store the async result so that I can look at it again later
#!/usr/bin/env python
"""Page views."""
from flask import render_template, request
from flask import Flask
from celerytest import add
from time import sleep
app = Flask(__name__)
async_res = []
#app.route('/', methods=['GET', 'POST'])
def run():
if request.method == 'GET':
return render_template("template.html")
else:
form = request.form
n1 = str(form.get("n1"))
n2 = str(form.get("n2"))
aysnc_res = add.delay(n1,n2)
return render_template("loading.html")
#app.route('/loading')
def check_if_complete():
if async_res.ready() == True:
return render_template("template2.html", val=async_res.get())
else:
sleep(5)
return render_template("loading.html")
if __name__ == '__main__':
app.run()
It appears that storing async_res as a global variable in my flask app causes server errors. So what's the best method of storing the result so that I can check on it in my "loading page"
I ended up being able to save the ID of my task in the session dictionary in Flask
See code below:
#!/usr/bin/env python
"""Page views."""
from flask import render_template, request
from flask import Flask
from celerytest import add
from time import sleep
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def run():
if request.method == 'GET':
return render_template("template.html")
else:
form = request.form
n1 = str(form.get("n1"))
n2 = str(form.get("n2"))
aysnc_res = add.delay(n1,n2)
session['TASK_ID'] = async_res.id
return render_template("loading.html")
#app.route('/loading')
def check_if_complete():
aysnc_res = session['TASK_ID']
if async_res.ready() == True:
return render_template("template2.html", val=async_res.get())
else:
sleep(5)
return render_template("loading.html")
if __name__ == '__main__':
app.run()

Categories

Resources