0

I'm trying to get the url of a webpage and store it as a variable, so that I can use that variable in a separate python program.

I'm new to flask, but I'm pretty sure that the commented code below can only work locally... I can't think of a way to make a global variable.

import random
from io import BytesIO
from flask import Flask, make_response,Response,request
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.pyplot as plt 


app = Flask(__name__) 

@app.route('/')
def plot():
    fig, ax = plt.subplots(1,1,figsize=(16,5))
    ax.plot(range(100), [random.randint(1, 50) for x in range(100)])
    canvas = FigureCanvas(fig) 
    output = BytesIO() 
    canvas.print_png(output) 
    response = make_response(output.getvalue()) 
    response.mimetype = 'image/png' 
    return response 

# var = request.root_url

if __name__ == '__main__':
    app.run(debug=True)

EDIT: Moderators, as I have said, I wanted to use the variable in another program. NOT necessarily between flask pages. Ergo, this is not a duplicate.

Matthew K
  • 189
  • 2
  • 12

1 Answers1

1

In a flask application, you have a Flask server with multiple threads and processes handling requests. If you make a global variable and would try to make use of it at different locations then many things would come into the picture(locks, mutexes, etc).

The problem is that you can't easily control threads and processes which would work on the global variable and its a bad practice too. This would show unexpected results as well.

All requests should always be independent of each other and should be stateless. Use a database or caching system (Memcache, Flask-Cache), which will handle the state for you(instead of a global variable). This would seem like an overhead but its simple and the best way to do things.

These articles would help you implement caching data with flask :

  1. http://brunorocha.org/python/flask/using-flask-cache.html

  2. https://blog.ruanbekker.com/blog/2019/02/14/how-to-cache-data-with-python-flask/

Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33