Access back-end console for Flask app deployed using Nginx and WSGI

I’m new to this domain so hopefully my question is not too elementary. I built an file that used pre-trained serialized machine learning models (pickle format) and gave prediction results when received POST-request from the front end user inputs. These inputs are also stored in MongoDB.

I run the using the method:


instead of : export then flask run --host=

The reason is because the former method allows the back-end to take in the pre-trained pickled model while the latter method somehow skipped this step. The result works like a charm in localhost.

Now I’m trying to deploy it to a real web domain. I use an ubuntu virtual server (DigitalOcean) to deploy the app using Nginx and WSGI. I successfully access my domain and see the html file rendered by Nginx. However, when I input the user information, I got in client console an internal server error 500.

I wish to access the back-end console to see what’s going on there but have no idea how to do it on the virtual server. I have spent too much time on this. Any help/direction will be much much appreciated.

P/s: Also, if somebody knows how to use the former method (mentioned above) for deployment in nginx and wsgi, please share 🙂 Right now, I’m starting the app using the command

systemctl start nginx 

import value javascript to flask

Я новичок в разработке на python и в целях изучения языка решил написать простую статистику сайта. Я создал свой локальный сервер на flask и несколько html страничек. Для показа статистики использую метод request. Вывод статистики делаю вот так:

    from flask import Flask , request   def main():     f = open('users.txt', 'a')     if request.environ.get('HTTP_X_FORWARDED_FOR') is None:         ip = (request.environ['REMOTE_ADDR'])     else:         ip = (request.environ['HTTP_X_FORWARDED_FOR'])     f.write('New connect ' + str( + ' IP address: ' + ip + ' ' + str(headers) + '\n')     f.close() 

Мне стало интересно , как получить разрешение экрана пользователя сайта, и я добавил в код html скрипт js который может выводить разрешение экрана. Выглядит так:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Start page</title> </head> <body> example page <br> <a class="Link" href="">Link to gallery</a> <a class="Link" href="">Link to about</a> </body> </html>  <script language=JavaScript> r1=(screen.width+'*'+screen.height+'&nbsp;'); document.write(r1) </script> 

То есть при запуске сервера и подключении на эту страницу мне выводит мое разрешение в цифрах. Но как мне эту цифру импортировать в файл .py и использовать для записи статистики?

Internal Server Error on Apache2 with flask

I’ve built a simple web app that runs perfect in localhost but now I’m trying to get it on the internet but I hit a 500 error.

import os from flask import Flask, render_template, redirect, request, send_file  from validator import validator, generate_token  app = Flask(__name__) @app.route("/",methods=["GET","POST"]) def hello():     try:         if request.method == "POST":             uri = request.form['uri']             id = validator(uri)             if id != 0:                 token = generate_token()                 command = './ ' + id + ' ' + token                 os.system(command)                 return redirect("/download/" + token, code=302)     except as e:         print(e)     return render_template("index.html")  @app.route("/download/<token>") def download(token):     return send_file(f'../songs/{token}.zip', cache_timeout=-1)  if __name__ == "__main__": 

When I try to run the .py file in the server with


it gives me the following error:

File "", line 24     return send_file(f'../songs/{token}.zip', cache_timeout=-1) 

Any hint on what is happening?

Preciso de uma recomendação sobre o modo de uso do bootstrap como formatação de templates em uma app Flask

Olá, esta dúvida parece meio básica mas ainda não achei uma resposta consistente. Gostaria de saber se, ao utilizar o Bootstrap como formatação de um template no FlaskPy, a melhor opção é via CDN, ou seja, anexando o link no arquivo.html […]

CSS only  <link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">  JS, Popper.js, and jQuery  <script src="" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapc

[…] ou devo baixar os arquivos e anexar na pasta static do app? Em algum dos casos tenho alguma perda de desempenho em meu app?

Uma observação: não desejo fazer alterações CSS na estrutura do Bootstrap, apenas usar as formatações básicas disponível pelo framework.

Desde já agradeço a atenção de vocês!

recommendations for a testing framework for Python backend on Flask

I hope this is the right place to ask something like this. I’m working on a bunch of relatively new (~3-9mo old) code at a new startup, and while the overall architecture is pretty solid, we don’t have a testing solution to speak of. We do test, but all of the tests are ad hoc for whatever changes are being made – nothing is automated. Partly as a result, people are afraid to touch code they haven’t touched in a while and I think development is at risk of slowing down.

I’m basically seeking recommendations for good testing software solutions… sadly I don’t have much experience with testing solutions or I wouldn’t have to ask. Ideally, I’d like a solution where we can gradually expand our coverage over time for existing code, while writing new tests from the start for new code.

I would like to experiment with something like TDD because I think that’s where I want to go ultimately, but I’m not dead set on something having to be TDD, and ideally a solution would be flexible enough that it can work even if I’m not doing that.

Our tech stack is basically Python on Flask, for both web services and batch jobs.

I’m not sure that it matters how we deploy it, but for what it’s worth we’re running on a combination of AWS Lambda (with AWS App Gateway) and AWS ECS (Fargate).

We also have a front end, but I’m treating testing that as a separate issue.

Flask WTForms same field IDs

I have a form in which if you tick a box, a lot of the inputs become disabled.

Here is a snippet of the form fields:

holiday_sick = BooleanField('Holiday or Sick?', id="holsick", validators=[Optional()]) start_time = TimeField(label='Start Time', id='timepick1', format='%H:%M', validators=[OptionalIf('holiday_sick')]) end_time = TimeField(label='End Time', id='timepick2', validators=[OptionalIf('holiday_sick')]) driving_hours = TimeField(label='Driving Hours', id='timepick3', validators=[OptionalIf('holiday_sick')]) 

The OptionalIf() is a custom validator that makes a field optional if the box is ticked — this works. However, I have to have to have multiple IDs and have to have multiple getElementByIds in my JS code — now I know that this gets the first element on the page with that name, and that having multiple IDs is bad practice. But how would I limit the amount of IDs (or similar) to just one?

My javascript code is this with multiple IDs:

document.getElementById('timepick1').disabled = this.checked; document.getElementById('timepick2').disabled = this.checked; document.getElementById('timepick3').disabled = this.checked; 

This is within .onchange for the holsick checkbox. I was wondering if there was anyway to just have one ID (or similar) within WTForms to correspond to multiple fields? I’ll potentially have more fields that will need to be disabled on holsick being ticked, so it would be more efficient to have one ID for all.

Flask, how to share common design data between templates

Im developing an app in flask. I have to tables, one renders on the server side using jinja2 and the other one is a live table that renders dinamically using socketio. They are in different routes but the tables look the same in design.

My problem relies on the rendering, i iterate through the same database in both cases but in the dynamic part i get the json and render it with mustache and the static table do the same but with jinja2. I need to store data related with states and categories that i obtain from the database for every row and use it for rendering in both routes.

basically i want to know where to store this relationship:

{id_in_db:{icon:x, color:y, name:z}}

im almost sure that whatever solution i get i would eventually need this as a jquery object (my current solution but a single change in that data means change multiple places on different templates) so i can then access on rendering to get the dynamic data, but… that doesn’t mean i now how to get there nor how to share the same data structure between flask jinja and js. Thanks in advance.