How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?
Running the app in debug mode will show an interactive traceback and console in the browser when there is an error. As of Flask 2.2, to run in debug mode, pass the --app and --debug options to the flask command.
$ flask --app example --debug run
Prior to Flask 2.2, this was controlled by the FLASK_ENV=development environment variable instead. You can still use FLASK_APP and FLASK_DEBUG=1 instead of the options above.
For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:
$ export FLASK_APP=example
$ export FLASK_DEBUG=1
$ flask run
For Windows CMD, use set instead of export:
set FLASK_DEBUG=1
For PowerShell, use $env:
$env:FLASK_DEBUG = "1"
If you're using the app.run() method instead of the flask run command, pass debug=True to enable debug mode.
Tracebacks are also printed to the terminal running the server, regardless of development mode.
If you're using PyCharm, VS Code, etc., you can take advantage of its debugger to step through the code with breakpoints. The run configuration can point to a script calling app.run(debug=True, use_reloader=False), or point it at the venv/bin/flask script and use it as you would from the command line. You can leave the reloader disabled, but a reload will kill the debugging context and you will have to catch a breakpoint again.
You can also use pdb, pudb, or another terminal debugger by calling set_trace in the view where you want to start debugging.
Be sure not to use too-broad except blocks. Surrounding all your code with a catch-all try... except... will silence the error you want to debug. It's unnecessary in general, since Flask will already handle exceptions by showing the debugger or a 500 error and printing the traceback to the console.
You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.
From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:
export FLASK_APP=/daemon/api/views.py # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
One can also use the Flask Debug Toolbar extension to get more detailed information embedded in rendered pages.
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
import logging
app = Flask(__name__)
app.debug = True
app.secret_key = 'development key'
toolbar = DebugToolbarExtension(app)
#app.route('/')
def index():
logging.warning("See this message in Flask Debug Toolbar!")
return "<html><body></body></html>"
Start the application as follows:
FLASK_APP=main.py FLASK_DEBUG=1 flask run
If you're using Visual Studio Code, replace
app.run(debug=True)
with
app.run()
It appears when turning on the internal debugger disables the VS Code debugger.
If you want to debug your flask app then just go to the folder where flask app is. Don't forget to activate your virtual environment and paste the lines in the console change "mainfilename" to flask main file.
export FLASK_APP="mainfilename.py"
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
After you enable your debugger for flask app almost every error will be printed on the console or on the browser window.
If you want to figure out what's happening, you can use simple print statements or you can also use console.log() for javascript code.
To activate debug mode in flask you simply type set FLASK_DEBUG=1 on your CMD for windows, or export FLASK_DEBUG=1 on Linux terminal then restart your app and you are good to go!!
Install python-dotenv in your virtual environment.
Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file
Inside this file write the following:
FLASK_APP=myapp
FLASK_ENV=development
Now issue the following command:
flask run
When running as python app.py instead of the flask command, you can pass debug=True to app.run.
if __name__ == "__main__":
app.run(debug=True)
$ python app.py
with virtual env activate
export FLASK_DEBUG=true
you can configure
export FLASK_APP=app.py # run.py
export FLASK_ENV = "development"
to start
flask run
the result
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: xxx-xxx-xxx
and if you change
export FLASK_DEBUG=false
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
For Windows users:
Open Powershell and cd into your project directory.
Use these commandos in Powershell, all the other stuff won't work in Powershell.
$env:FLASK_APP = "app"
$env:FLASK_ENV = "development"
If you have PyCharm Professional, you can create a Flask server run configuration and enable the FLASK_DEBUG checkbox. Go to Run > Edit Configurations, select or create a Flask server configuration, and enable the FLASK_DEBUG checkbox. Click OK, then click the run button.
You can install python-dotenv with
pip install python-dotenv then create a .flask_env or a .env file
The contents of the file can be:
FLASK_APP=myapp
FLASK_DEBUG=True
Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.
Is there a straightforward way to run Puppeteer on wsl2? I've tried many solutions across the web and read tons of forums looking for answers. So far no success and I've found running Puppeteer very easy in windows but extremely difficult in wsl2.
I've tried downloading chrome and chromium, and specifying the executablePath with no luck.
I know that it works on my windows system, but cannot seem to get Puppeteer to run in wsl2.
I am currently stuck on this error:
Timeout Error: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r1022525 is guaranteed to work.
When looking into node_modules I can see that version 1022525 is in use. I can't understand what Puppeteer's problem is nor how to fix it.
Anyone have any ideas?
As I do not see exactly what are you trying to do , in the moment I can think that this error accused because of your windows defender firewall, which do not allow access of your X-server.
anyway for me I use Puppeteer on wsl2 as following:
I need to install VcXsrc as X-server to display what is going on in the Linux side of the computer. https://sourceforge.net/projects/vcxsrv
notes: you need to allow “Public networks” when the Windows firewall pops up.
You need now to set a DISPLAY environment variable has to be set,becuase wsl has its own IP address, we need to connect to our X-server app using this IP so to do this follow the next steps.
In your .bashrc (or .zshrc if you are using ZSH) add this line exactly to the end:
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0.0
now executes the content of your bash use source ~/.bashrc (or source ~/.zshrc if you are using ZSH)
to be sure that your DISPLAY environment variable has set correctly , try this command (echo $DISPLAY) the result should be something like this : # 172.16.210.1:0.0 it will be your wsl IP address.
now Open the VcXsrv program in Windows (called XLaunch), allow this options step after step “Multiple windows” and “Start no client”. and in the end tick the option of disable access control Be sure to disable access control.
as last check go to windows defender firewall and be sure that you enable all network connection for VcXSrv.
now you are ready to go, let suppose I am using puppeteer to test inside jest file like the follwoing :
const puppeteer = require('puppeteer');
test('should create an element...etc', async () => {
const browser = await puppeteer.launch({
headless: false,
args: ['--window-size=1920,1080']
});
const page = await browser.newPage();
await page.goto(
'www.google.com'
);
});
start the last code using (jest nameofyourtestfile) and your puppeteer will work as you like, Chromium will open in your windows ...enjoy...if there is any details which is not clear may you ask again. I hope that I helped
I have installed the MS4W map server and when I try to launch the site in the localhost it takes me to the below landing page. I am unable to see the map getting loaded in the page.
Any suggestions?
Besides using the setup.exe installer from https://ms4w.com, you can install MS4W manually as well, using the .zip available there; you can use the steps below to verify your installation either way:
make sure that you installed/extracted MS4W into a root of a drive (for example,
you should have a resulting directory structure such as:
C:/
ms4w
Apache
apps
...
open a command prompt window (use Windows search, enter "cmd", and make sure to
choose "Run as Administrator"
now in Command Prompt, enter:
cd c:/ms4w
then setup the MS4W environment with:
setenv.bat
which should let you know that the MS4W environment is ready:
GDAL, mapserv, Python, PHP, and commandline MS4W tools path set
now we can install the Apache web server:
apache-install.bat
which should display a successful message such as (notice the text "The Apache MS4W Web Server service was started successfully") :
Installing the 'Apache MS4W Web Server' service
The 'Apache MS4W Web Server' service is successfully installed.
Testing httpd.conf....
Errors reported here must be corrected before the service can be started.
The Apache MS4W Web Server service is starting.
The Apache MS4W Web Server service was started successfully.
if you have errors, you can check the Apache logs at C:/ms4w/Apache/logs
you can also verify that MapServer is ready at the commandline, with:
mapserv -v
which should display MS4W information such as:
MapServer version 7.6.0-dev (MS4W 4.0.3) OUTPUT=PNG OUTPUT=JPEG OUTPUT=KML SUPPORTS=PROJ SUPPORTS=AGG SUPPORTS=FREETYPE SUPPORTS=CAIRO SUPPORTS=SVG_SYMBOLS SUPPORTS=SVGCAIRO SUPPORTS=ICONV SUPPORTS=FRIBIDI SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER SUPPORTS=SOS_SERVER SUPPORTS=FASTCGI SUPPORTS=THREADS SUPPORTS=GEOS SUPPORTS=POINT_Z_M SUPPORTS=PBF INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE
TIP: try to now execute other MS4W tools at that same commandline, such as gdalinfo --formats or shp2img etc. (basically you can call any tool now, that lives in C:/ms4w/tools, without ever having to change directory there)
now you are ready to goto your localhost, so open your web browser (Firefox, Chrome, IE) and type: 127.0.0.1 <enter>
you should see the MS4W homepage now in your local browser, with a sample map as well (that is actually a fully configured WMS service served from your local machine, serving Spatialite data), such as: https://ms4w.dev/
Is there an option to enable Chrome or the Internet Explorer to load (via ajax-get) an JSON file from the local harddisk?
Firefox does so by default. Internet Explorer says 'premission denied' at the line
request.open(method, url, true);
There are no simple cleaner way you can do this, you have to do some server-side coding.
I suggest you node.js this is very handy for this type of IO operations.
It looks very difficult for first time but it is very handy.
Download and install nodejs.
create a simple project to handle this.
In the directory you want files to get (e.x. D:\myfiles), create one file server.js, content of that js file would be following
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic("./")).listen(105);
open command promp from and get to this directory (D:\myfiles)
Run these two commands npm install connect and npm install serve-static (up to this, is one time process)
Run node server.js - That's all your server is ready and running
call http://localhost:105/<file name> and you can get any files within that directory.
For chrome you can use following command line flags, taken from following question
--allow-file-access-from-files
--disable-web-security
As noted in that question you need to restart your all chrome browsers.
For internet explorer, trick is to use ActiveX version of the XMLHttpRequest object.
See following link.
https://social.msdn.microsoft.com/Forums/ie/en-US/9ae077e0-a7b9-433f-835f-2643aa1a7e09/ie11previewcannot-read-local-files-with-ajax-method-of-jquery?forum=iewebdevelopment
I'm using the mean stack and intelliJ. Whenever I run my node.js server I see this output in the intelliJ console:
path/bin/node --debug-brk=32865 server.js
debugger listening on port 32865
Express app started on port 3000
Then I browse to localhost:3000/#!/test I just get a blank page. But it shows that I hit it in my intelliJ console. Also if I just go to localhost:3000/test it shows the correct json for the page. So its almost like its not aware of my html and css somehow?
How can I load my html and css correctly?
I just had to go into my root directory and run npm install.