modify content of flask page with another python script - python

I have two Python scripts:
tnk_flask.py: This creates a flask webserver and two pages.
pitoka.py: this creates a random number.
My goal is the following:
When I run pitonka.py, I always generate a random number which I'd like to pass to tnb_flask.py, but, after refreshing those pages nothing changes.
What can be the mistake?
tnb_flask.py:
from flask import Flask # ezzel importáljuk ki
from pitonka import *
app = Flask(__name__)
#app.route('/')
def index():
denis = alma()
return str(denis)
#app.route('/tuna')
def index__():
return str(numbi)
if __name__ == "__main__":
app.run(debug=True)
pitonka.py:
from flask import Flask
# import tnb_flask
import random
numbi = random.randint(10, 100)
print(numbi)
def alma():
return numbi + 17

In pitonka.py you are assigning the random number to a variable. So it will only get the random variable once. Instead return the random number in the function.
def alma():
return random.randint(10, 100) + 17

You could serve static pages via flask and re-render them from templates in pitonka.py

Related

Packaging a python script from another repository into flask

I was tasked with creating 2 repositories.. one has a simple python script
the other is a flask application which should use the first script and return the results in a json
so both projects look something like this
main.py
import random
def isPrime(n):
# Corner case
if n <= 1:
return False
# check from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
# Function to print primes
def printPrime(n):
previous_primes_nb = []
for i in range(2, n + 1):
if isPrime(i):
previous_primes_nb.append(i)
return previous_primes_nb
if __name__ == "__main__":
# randomized number
n = random.randint(2, 100)
# function calling
previous_primes_list = printPrime(n)
print(previous_primes_list)
simpleflask.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run(port=8777)
One way to achieve this is by creating a python package for main.py, and import that into your flask app.
Official doc on creating python packages.
Good tutorial on creating a package for internal use.
You can make that internal package available to the simpleflask.py making sure it's on the PythonPath envirnoment variable or you can use a tool like setuptools to distribute the package.

Display the stored value in variable by flask

I want to display the variable value using flask,
Here is the code which i have tried
from flask import Flask
app = Flask(__name__)
#app.route("/")
def get_values():
v1 = 1
return "v1"
if __name__ == "__main__":
app.run()
I need to display the value of v1 that is 1 in the application.
If you just want to serve a plain text response containing the string representation of the number in the v1 variable, all you need is:
return str(v1)

How to add multible #app.route in py editor?

Hear is my code:
from flask import Flask
from flask import Markup
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route("/")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
#app.route("/chart")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001)
The first #app.route("/") works correctly the second does not disappear any Chart like the first one. it disappears just some text of HTML. Any one can help?
First, you don't need to import Flask twice so you can delete one line of
from flask import Flask
The reason it's not working is because you defined two of the same functions 'chart()'. There also seems to be something wrong with the name 'chart' as a route, if you change that, it should be working.

Python - Flask - open two webpages in default browser

The following code is a variation on the answer given here.
Two webbrowser.open() are requested, and they are spaced out slightly in time.
Two web pages are rendered all right, but both show the second (Chris) parameter.
Why is Pat not greeted?
import random, threading, webbrowser
from flask import Flask, render_template_string
app = Flask(__name__)
#app.route('/<name>')
def index(name):
return render_template_string('''<h3>Hello, {{ name }}!</h3>''', name=name)
if __name__ == '__main__':
names = ['Pat', 'Chris']
port = 5000 + random.randint(0, 999)
wait = 1.25
for name in names:
url = "http://127.0.0.1:{0}/{1}".format(port, name)
threading.Timer(wait, lambda: webbrowser.open(url)).start()
wait += 0.5
app.run(port=port, debug=False)
Defining a callback function in a loop is the problem, it's called late binding. Both lambdas ultimately see the last value of url. Replace the lambda with:
functools.partial(webbrowser.open, url)
or scrap the timer and just time.sleep(0.5) in the loop.

Global variable is None instead of instance - Python

I'm dealing with global variables in Python. The code should work fine, but there is a problem. I have to use global variable for instance of class Back. When I run the application it says that back is None which should be not true because the second line in setup() function - 'back = Back.Back()'
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request
from flask import render_template
import Search
import Back
app = Flask(__name__)
global back
back = None
#app.route('/')
def my_form():
return render_template('my-form.html')
def setup():
global back
back = Back.Back()
def is_ascii(s):
return all(ord(c) < 128 for c in s)
#app.route('/', methods=['POST'])
def search():
from time import time
pattern = request.form['text']
startTime = time()
pattern=pattern.lower()
arr = []
if len(pattern)<1:
arr.append('Incorrect input')
currentTime = time()-startTime
return render_template('my-form.html', arr=arr, time=currentTime)
arr = []
search = Search.Search(pattern,back)
results = search.getResults()
..................
return render_template('my-form.html', arr=arr, time=currentTime, pattern=pattern)
app.debug=True
if __name__ == '__main__':
setup()
app.run()
Why is the back variable None instead of instance of Back class? Thanks
The Flask development server runs your module twice. Once to run the server itself, and another time in a child process so it can reload your whole script each time you make a change to it. It is that second process that won't run the __main__ guarded code and the global is left as None.
You'll get the same problem if you used another WSGI server; it'd import your file as a module, not as the initial script and the __main__ guard is not executed.
Use a #app.before_first_request function instead; it is guaranteed to be executed when the very first request is handled for this process. This also keeps your global working if you moved to a proper WSGI container that used multiple child processes to scale your site:
#app.before_first_request
def setup():
global back
back = Back.Back()

Categories

Resources