Abort a function if it doesn’t finish executing by n seconds in Python Flask

I’m building an API with the Flask library in Python. In my API, I try to call a function that may take a while to finish executing. Sometimes it finishes in less than a second, and sometimes it takes a few minutes. How do I kill it if it takes more than 12 seconds without actually sleeping for 12 seconds in my program?

from flask import Flask
from multiprocessing import Process

app = Flask(__name__)

def evaluate(to_eval):
 # ... (might take a while)
 evaluated = <evaluated>
 return evaluated

@app.route('/api/')
def api():
 # ...
 to_eval = <some_value>
 process = Process(target=evaluate, args=(to_eval,))
 evaluated = None
 status = 'success'
 process.start()
 process.join(12)
 if process.is_alive():
  process.terminate()
  process.join()
  status = 'timeout'
 return {'evaluated': evaluated, 'status': status}

I tried the above, but it sleeps for 12 seconds even if the function finishes executing in less than a second. I want the response to be returned if the function finishes executing by 12 seconds. If it doesn’t, the code should return a response with an error message saying “Timeout” or something like that.

Can someone please help?

man in the middle – Best way to MITM own flask website?

I’m a beginner, trying to implement an ssl-stripping attack on my own Flask site running on localhost to fully understand how it works. My thinking was to set up a proxy server that I controlled and be able to see requests coming through the proxy server, using the proxy to downgrade the site to HTTP when sending it back to my own browser. This would ideally be all running on my own computer.

I found some code to run a proxy server in Flask as well, found here. It’s not exactly what I want, because it doesn’t render out the site completely- images and javascript are not rendered, for instance, so it’s not completely convincing. Google, for example, looks like this (my own site is similarly stripped down to the bare bones):

enter image description here

Is there a better way to approach this other than a proxy server and/or how can I make this proxy look more convincing when I visit a site? I know there are tools available for ssl-stripping, I thought it would be an interesting experiment to try and manually do as much of the attack as possible.

Nginx + Gunicorn + Flask not serving static files

I am new to Nginx and Gunicorn….

I am trying to serve flask app on certain prefix….

ex: https://myweb.com/flask/prefix/

everything works fine except it is not loading static files……

my nginx site configuration looks like below

location /flask/prefix/ {
        include proxy_params;
        proxy_pass http://unix:/home/user/flask_config/flask_socket_file.sock:/;        
    }

when I checked the network section by using Firefox developer tool I found that it is loading home page path / for static files instead of this /flask/prefix….

Example:

/static/image.png (i.e https://myweb.com/static/image.png)

but it suppose to be /flask/prefix/static/image.png (i.e https://myweb.com/flask/prefix/static/image.png).

However I tried to remove :/ at the end of proxy_pass statement… it ended with 501 error….

Please let me know what I am doing wrong….

I followed steps to configure Flask app with Nginx from Here

tls – Can a machine running a packet sniffer see what nginx is forwarding on localhost to a Flask app?

I want to serve a Flask application from my pc. Other machines in my network only should be able to consume the API. However, I wish to have the communication between the other machines and the API secured using https with a self-signed certificate. For this reason (because serving Flask with waitress does not support https on its own), I am using nginx on the same machine as a proxy so that it can handle https.

My question is:
If someone connects to my network, let’s say via wifi, and runs a packet sniffer like Wireshark, will they be able to see what is being transferred between the legitimate clients of the app and the app?

When running Wireshark on the same machine as the application, I see the request and all of its contents. I believe this is because it is sniffing on localhost and sees the forwarded http request (from nginx to the app). When running Wireshark on my laptop, I don’t see the http request. Can someone confirm this is safe for my purposes?

Also: Can someone confirm that if nginx were to run on a separate local machine, then the http request would be exposed again?

EDIT: Here is the nginx configuration I have

server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/sites-available/nginx-selfsigned.crt;
    ssl_certificate_key /etc/nginx/sites-available/nginx-selfsigned.key;

    server_name example.com;

    location / {

        proxy_pass http://127.0.0.1:5000;
        proxy_set_header X-Real-IP $remote_addr;


    }
}

server {
  listen 80;

  server_name 192.168.1.5;

  return 301 https://$server_name$request_uri;
}

json – Run python File With get request flask API

Code is Working Review and Recommend What Are Best Practice

What I am trying to achieve.

  1. API with Flask that runs any python file from the current directory.

  2. Run the file and get output in JSON

Below is the code for the app.py

from flask import Flask,jsonify
from flask_restful import Api,Resource
import os

app = Flask(__name__)
api = Api(app)

class callApi(Resource):
    def get(self,file_name):
        my_dir = os.path.dirname(__file__)
        file_path = os.path.join(my_dir, file_name)
        file = open(file_path)
        getvalues={}
        exec(file.read(),getvalues)
        return jsonify({'data':getvalues('total')})

api.add_resource(callApi,"/callApi/<string:file_name>")

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

Below is the code for the main.py which sends a request to API.with Filename which to run.
The filename will be changed as per requirements.

import requests

BASE = 'https://127.0.0.1/callApi/runMe.py'

response = requests.get(BASE)
print(response.encoding)

Below is the File which runs by exec from API
API/app.py can access this file because both are in the same dir.

def fun():
    a = 10
    b = 10 
    total = a+b
    print(total)
    return total
 
total = fun()

Is there any better way to write all this code please let me know.
here are refs which I used to make this

Eval function

Exec Function

Exec Docs

Running a python script saved in local machine from google sheets on a button press

Tomar solo un valor de una consulta MySQL en Flask Python

Tengo una consulta en Flask Python Mysql, y necesito tomar solo uno de los valores para asignarlo a una variable, el valor que necesito tomar es e_grado:

    cur = mysql.connection.cursor()
    cur.execute('select e_id, e_nombres, e_apellidos, e_grado, a_docident, a_nombres, a_apellidos, a_telefono from estudiantes INNER JOIN acudientes ON e_acudiente = a_id  where e_id = {0}'.format(e_id))
    data = cur.fetchall()
    grado = cur.fetchone(3)

Ese valor e_grado necesito asignarlo a la variable grado, ¿cómo puedo hacerlo?, traté de hacerlo con grado = cur.fetchone(3) pero veo que no es la manera correcta.

Muchas gracias.

dnd 5e – Does Iron Flask work on player characters?

The flask has no effect on most PCs while on the Material Plane

When you target a creature with the flask:

If the target is native to a plane of existence other than the one you’re on, the target must succeed on a DC 17 Wisdom saving throw or be trapped in the flask.

This effect only happens for creatures not native to the current plane. No effect is specified for a target that is native to the plane of existence, which means that if you are on the Material Plane and target a creature native to the Material Plane, the flask has no effect. The vast majority of playable races are native to the Material Plane, so they generally cannot be trapped by the flask under normal circumstances. However, there are exceptions, such as Eladrin (mechanically a sub-race of elves), who are “native to the Feywild”. An eladrin on the Material Plane can be affected by the flask.

However, if the party were to make an excursion to another plane, such as the Feywild, the PCs would indeed be vulnerable to the flask’s effect while they are not on the Material Plane. Conversely, an Eladrin PC would be immune to the flask while on the Feywild, since it is their native plane.

It may even be beneficial for a PC to use the flask on another PC under some rare circumstances, since the requirement to obey another PC’s orders might help override an enemy charm or mind control effect. This would obviously require quite a lot of trust, both in and out of character.

python – Problema na importação no Flask (Unable to import ‘controllers’ pylint(import-error)

Boa noite, estou começando a programar agora e estou tentando fazer um sistema simples usando o framework Flask, porém durante a organização dos arquivos me deparei com o problema do título, não estou conseguindo importar o default localizado na pasta controllers, onde que eu estou errando?organização do sistema e onde o erro de import está aparecendo

elastic beanstalk – Nginx + uWSGI + Flask Connection Reset

Problem

I have a Flask app deployed using Elastic Beanstalk’s “Single Container Docker” platform (latest revision 3.2.5 at the time of writing), with an “Application Load Balancer” in front of it. I had this same Flask app deployed in EB with the “Python 3.6” platform (and a “Classic Load Balancer”) for ages, but have since started having issues after upgrading to the new deployment. I am a relative novice when it comes to configuring Nginx / uWSGI, bear with me…

Specific Issue

I see the following errors in my Nginx error.log file on ~0.01% of the requests my environment handles:

<timestamp> (error) 22400#0: *52192 upstream prematurely closed connection while reading response header from upstream, client: <ip>, server: , request: "POST <endpoint> HTTP/1.1", upstream: "http://<ip>:5000/<endpoint>", host: "<my hostname>"
...
<timestamp> (error) 22400#0: *101979 readv() failed (104: Connection reset by peer) while reading upstream, client: <ip>, server: , request: "POST <endpoint> HTTP/1.1", upstream: "http://<ip>:5000/<endpoint>", host: "<my hostname>"

I see these errors across requests to different endpoints, using different HTTP methods (GET and POST), and at seemingly random times. Additionally, I do not see any application errors in my Flask app logs, which indicates that this is not an application issue but rather a configuration one.

Discussion

I ended up reading and trying a lot of stuff, so I’ll recount my experience for posterity. The answer I arrived at seems so simple that I’m still suspicious that I’ve got it right.

From the reading I’ve done, this sounded like a pretty straightforward issue with some misconfigured timeouts between Nginx + uWSGI. I was encouraged after reading this post which describes almost my exact situation with Elastic Beanstalk.

Part 1: Semi-Random Flailing

In the numerous and varied answers on this post I found some things to try:

  1. I tried setting the uWSGI parameter post-buffering = 32768 since people suggested that. It did not help, which makes sense because the setting applies only to requests with a Body and I had been observing the aforementioned errors on GET requests as well.
  2. I tried playing with Nginx’s keepalive + keepalive_timeout and uWSGI’s so-keepalive, http-timeout, and socket-timeout.

I realized from reading the docs that these uWSGI settings definitely weren’t going to help, although I held out hope for so-keepalive.

At this point I did notice a relatively significant decrease in the frequency of these errors, but they did not go away altogether. Like a bad engineer, I changed multiple variables at once in some of these trials. Thus, it’s hard to know exactly what helped. I suspect I made things better by setting Nginx keepalive to a number of connections <= what I saw was the maximum connections it could handle in the uWSGI log (100 connections). Anyone else’s insight on that one is welcome, albeit there’s not much to go on…

Part 2: A fix, I think…

I decided to try overriding the default upstream definition Elastic Beanstalk puts into the Nginx config. The original looked like this:

upstream docker {
    server <some ip>:5000;
    keepalive 256;
}

All I did was replace this with my own upstream, change the Nginx location to point at my custom upstream (below) and simply not set the keepalive parameter. Like so:

upstream myapp {
    server <some ip>:5000;
}
...
location / {
    # proxy_pass http://docker;
    proxy_pass http://myapp;
}

This seems to work… Since putting in the change I have basically seen zero 5xx errors in my Elastic Beanstalk environment. The fact that this works also seems to be corroborated by this answer which mentions:

… a uwsgi connection isn’t reusable and so it gets closed and a new connection opened with every request; it wouldn’t remain idle for any significant amount of time in normal operation.

I’m not sure where that is documented, but I didn’t notice it when reading about using uWSGI + Nginx. If that’s accurate, it certainly explains a lot.

Conclusion / Help?

I’m really glad I was able to figure this one out and the API seems to be working really well, but I can’t kick the feeling that I don’t understand why this works or I’ve committed some grave sin with this configuration.

It felt a bit cumbersome to override this stuff in Elastic Beanstalk, which makes me think I shouldn’t have. With the popularity of uWSGI for python webapps, my spidey-sense is telling me that there should have already been numerous posts about this Nginx keepalive playing poorly with uWSGI. Especially since that’s in the default configuration for this Elastic Beanstalk platform.

If you’ve read this far and know things, feel free to weigh in on the situation. Hopefully, at the very least, the next person to see those errors in their Nginx logs has another data point as to what the problem could be.