Deploying a Flask application using cgi script in Xampp - python

I am attempting to deploy a simple Hello World script on XAMMP.
In case the link is removed here is application.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
My applciation.cgi script is as follows:
#!C:/Users/Simon/Documents/Python/Scripts/python.exe
from wsgiref.handlers import CGIHandler
from application import hello
CGIHandler().run(app)
C:/Users/Simon/Documents/Python/ is the location of my virtual python environment.
I have configured XAMMP (httpd.conf) in the following way:
AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict
This configuration I kept in all cases.
I tried the following as suggested in the documentation:
ScriptAlias /Network C:/Users/Simon/Documents/Network/application.cgi
This failed and I tried this as suggested in here:
<Directory "C:/Users/Simon/Documents/Network">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
Alias /Network "C:/Users/Simon/Documents/Network"
In all cases an Error 500 Server error! was returned.
I'm not sure if it's needed but here is the relevant error showing in access.log:
192.168.0.8 - - [17/Feb/2018:13:21:12 +0000] "GET / HTTP/1.1" 500 1100 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36"
If anything is missing please tell me and I will add it.
How can I correctly configure my server so that I can run this script?
There was mistake in application.cgi:
#!C:/Users/Simon/Documents/Python/Scripts/python.exe
from wsgiref.handlers import CGIHandler
from application import hello
CGIHandler().run(hello)
It is however still returning an error:
A server error occurred. Please contact the administrator.

You've imported the wrong thing in your CGI script; as a result app is not defined. You should be importing that rather than hello.

Related

Issues getting nginx to serve my flask app

The bounty expires in 4 days. Answers to this question are eligible for a +350 reputation bounty.
dms_quant wants to draw more attention to this question.
I have a flask app that I would like to serve via a DO Droplet.
I have followed How To Serve Flask Applications with Gunicorn and Nginx on Ubuntu 22.04
This is my folder structure
root/
└── baseweb/
├── venv
├── app.py
└── app/
├── routes.py
└── templates/
└── index.html
app.py looks like this
from app import app
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
I have created a baseweb service
[Unit]
Description=Gunicorn instance to serve myproject
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/baseweb
Environment="PATH=/root/baseweb/venv/bin"
ExecStart=/root/baseweb/venv/bin/gunicorn --workers 1 --bind unix:baseweb.sock app:app
[Install]
WantedBy=multi-user.target
and my nginx configuration (/etc/nginx/sites-available/baseweb) - edited per arthur simas comment below
server {
listen 80;
server_name baserank.net www.baserank.net;
location / {
proxy_pass http://unix:/root/baseweb/baseweb.sock;
}
}
When i simply run app.py using my venv, i can access my flask app via http://68.183.68.148:5000/
if I run gunicorn --bind 0.0.0.0:5000 app:app i can also access my app via the same IP.
But when i try to access via nginx (via http://68.183.68.148 without running the app in console), i get
502 Bad Gateway
nginx/1.22.0 (Ubuntu)
I have spent hours trying to adjust settings, but i have no idea where this is going wrong - so any help is very much appreciated.
Edit 2023-02-17: Ngnix access.log
185.16.141.5 - - [17/Feb/2023:14:14:17 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:17 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:20 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
185.16.141.5 - - [17/Feb/2023:14:14:20 +0000] "GET / HTTP/1.1" 502 568 "http://baserank.net/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
143.110.222.166 - - [17/Feb/2023:14:22:21 +0000] "GET / HTTP/1.1" 502 166 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1"
your ngnix config is wrong. you don't use root directive for reverse proxying with nginx, but instead proxy_pass. the tutorial you've posted is right. the changes you should do:
server {
listen 80;
server_name your_domain www.your_domain; # place here your website domain (optional directive)
location / {
proxy_pass http://unix:/root/baseweb/baseweb.sock;
}
}
listen tells were the nginx server should listen to requests. it could be only the port (80), ip:port (68.183.68.148:80), an unix socket (unix:/var/run/nginx.sock), etc...
the proxy_pass directive acts as a reverse proxy, forwarding traffic to the provided URL.
root is for serving static files.
read more at:
NGINX Module ngx_http_core_module - listen
NGINX Reverse Proxy
NGINX Module ngx_http_proxy_module - proxy_pass
Serving Static Content
also, be sure to create the service in systemd, at the correct path location and check if its running sudo systemctl status myproject (or nginx would not be able to forward traffic to it)
One potential issue could be with the ownership and permission of the socket file /root/baseweb/baseweb.sock. Make sure the user running the Gunicorn service (in your case, root) has ownership of the file, and the permissions are set correctly. You can try changing the group to root in the baseweb.service file:
[Service]
User=root
Group=root
WorkingDirectory=/root/baseweb
Environment="PATH=/root/baseweb/venv/bin"
ExecStart=/root/baseweb/venv/bin/gunicorn --workers 1 --bind unix:baseweb.sock app:app
After modifying the service file, make sure to reload the daemon and restart the service:
sudo systemctl daemon-reload
sudo systemctl restart baseweb
You can also check the error log of Gunicorn by adding --log-level debug --error-logfile /path/to/error.log to the Gunicorn command in the baseweb.service file. Then, check the content of /path/to/error.log for more details about the error.
Another thing to try is to update the Nginx configuration to proxy pass to http://127.0.0.1:5000 instead of the socket file. You can try modifying the configuration file as follows:
server {
listen 80;
server_name baserank.net www.baserank.net;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
After modifying the configuration file, restart the Nginx service:
sudo systemctl restart nginx

Apache server in Linux error forbidden access

I'm a beginner in web development. When I run Apache server give me this error in web page:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
localhost
Apache/2.4.20 (Unix) mod_wsgi/4.4.22 Python/2.7.11
I'm developing using Django 1.9.1 web app and use mode_wsgi with apache version 2. Here is my wsgi.py file :
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "newSite.settings")
application = get_wsgi_application()
and my httpd.conf :
WSGIScriptAlias /newsite "/home/hello/django/newSite/newSite/wsgi.py"
WSGIPythonPath "/home/hello/django/newSite"
<Directory "/home/hello/django/newSite/newSite/">
<Files wsgi.py>
Require all granted
</Files>
</Directory>
thanks guys'
im succeed to run the server truely .
just change target directory permission to 775 and change the user and group in httpd.conf to my current user .
and for custom folder for sites root , change "DocumentRoot" of httpd.conf and set permission.
sory for my english.
thanks again

Flask website -- 500 Internal Server Error

I cannot for the life of me figure of why this flask application I'm trying to launch is not working. I am running it on a $5 Digital Ocean droplet. Here's (hopefully) everything you need to know about it:
Directory layout (contained within /var/www/):
FlaskApp
FlaskApp
__init__.py
static
templates
venv
flaskapp.wsgi
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "yay it worked"
if __name__ == "__main__":
app.run()
flaskapp.wsgi:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/FlaskApp/")
from FlaskApp import app as application
application.secret_key = 'Add your secret key'
FlaskApp.conf (contained in /etc/apache2/sites-availble):
<VirtualHost *:80>
ServerName the.ip.blah.blah
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
venv was created from calling virtualenv venv within /var/www/FlaskApp/FlaskApp/. I installed flask in venv using pip install flask after entering venv using source venv/bin/activate.
Wsgi has been enabled (a2enmod wsgi). FlaskApp.conf was enabled (a2ensite FlaskApp). And, finally, I restarted apache many times, but to no success (service apache2 restart).
I was following this guide on how to set up a flask application.
Here is a screenshot of what my error looks like:
Any help on getting this to work would be greatly appreciated.
Thanks in advance.
EDIT: I found the problem: ImportError: No module named flask. This is a little strange since I did do pip install flask within the virtualenv. When I just open a python console session in the virtualenv and try import flask I get no error, so not sure what's going on.
Also, how is this application even using venv? I don't see it getting accessed anywhere so how is it even using it? Perhaps this is why i'm getting the ImportError, because I only have flask installed on the virtualenv but it's not being used?
The problem is essentially that you are installing Flask, and possibly other required libraries, in a virtual environment but the python (wsgi interface) is running with the system python which does not have these extra libraries installed.
I have very little recent experience running Python on Apache (I come from an era of mod_python and cgi), but apparently one way to handle this is to use the site package to add the site-packages from your venv to the Python that is executed. This would go in your .wsgi file.
import site
site.addsitedir('/path/to/your/venv/lib/pythonX.X/site-packages')
I think the best way to solve your problem is to add tell your wsgi file about your virtual environment and activate it:
put the following code in your your flaskapp.wsgi
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
and restart apache.
hope it will help!
find more here

Why apache throws Target WSGI script not found or unable to stat on Flask app?

I want to setup my flask app for apache on my ubuntu server using wsgi. But after my setup, I get the following browser error:
Not Found
The requested URL / was not found on this server.
The apache error log throws:
Target WSGI script not found or unable to stat:
/var/www/html/appname/appname.wsgi
My wsgi file looks like this:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/html/appname/")
from IdeaHound import app as application
application.secret_key = 'here_the_key'
and my apache config file looks like this:
<VirtualHost *:80>
ServerName server_ip_here
WSGIScriptAlias / /var/www/html/appname/appname.wsgi
<Directory /var/www/html/appname/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel info
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
The appname folder has the following structure:
appname
--application.py
--appname.wsgi
--LICENSE
--README.md
--requirements.txt
--db_manage.py
--appname
----frontend
----__inity__.py
----__init__.pyc
----models
----__pycache__
----socket_interface
--AppName
----__init__.py
----static
----templates
--instance
----config.py
What am I missing here to make the webserver run correctly with Flask?
Please read the following link of Digital Ocean. Do as describe in it. And your app will be up and running in just 5 mins.
https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps
Also do check the apache error logs for more information if it still throws an error.
/var/log/apache2/error.log

flask app won't run on ubuntu 12.04 (digital ocean)

I am having difficulties deploying a basic flask app on a digital ocean server running ubuntu 12.04, apache2, and mod-wsgi. I have tried a number of different modifications of both the myapp.conf file and the myapp.wsgi file. I suspected that these were the culprits, but now I'm not so sure.
At all times, visiting my url just displays the apache 'It works' dialogue. Each attempt made to successfully restart the apache service (after trying to fix the problem), and access the website sees this same activity in the error.log:
[Wed Aug 27 00:49:14 2014] [notice] caught SIGTERM, shutting down
[Wed Aug 27 00:49:15 2014] [notice] Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured -- resuming normal operations
And this activity in the access.log:
11.22.33.44 - - [27/Aug/2014:00:49:19 -0400] "GET / HTTP/1.1" 304 209 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
11.22.33.44 - - [27/Aug/2014:00:49:21 -0400] "GET / HTTP/1.1" 304 208 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
11.22.33.44 - - [27/Aug/2014:00:49:24 -0400] "GET / HTTP/1.1" 304 208 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
By 'basic' flask app, I mean: no sql database (as in none, not as in non-relational), no site users, no factory, no blueprint, etc.
The relevant directory /var/www/myapp/ looks like this (using virtualenv to run the app):
myapp/
+ myapp/
| + static/
| + templates/
| + venv/
| | __init__.py
| myapp.wsgi
Although I have tried several versions of the myapp.conf file, these two are representative:
<VirtualHost *:80>
ServerName myapp.com
WSGIDaemonProcess myapp user=flask group=www-data home=/var/www/myapp/
WSGIScriptAlias / /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp/myapp/>
WSGIProcessGroup myapp
WSGIApplicationGroup % {GLOBAL}
WSGIScriptReloading On
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
And:
<VirtualHost *:80>
ServerName myapp.com
WSGIScriptAlias / /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp/myapp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/myapp/myapp/static
<Directory /var/www/myapp/myapp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
The two general types of myapp.wsgi files I have tried are:
#!/usr/bin/python
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/myapp/")
from myapp import app as application
And:
activate_this = '/var/www/myapp/myapp/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import os
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/var/www/myapp/')
from myapp import app as application
#commenting out same in __init__.py
if __name__ == '__main__':
application.run()
The app does run successfully on my local machine, and I always chowned the /var/www/ directory for each user identified in the .conf file.
Any thoughts, tips, pointers, etc are extraordinarily welcome. Thanks very kindly.

Categories

Resources