Deploying flask app to Apache shared hosting - python

I am trying to deploy a simple flask application in the Apache shared hosting server.
I am not sure what is wrong here.
I am stuck at the .cgi file for now.
The flask app - hello.py:
#!/usr/bin/python
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!\n"
if __name__ == "__main__":
app.run()
The myapp.cgi file:
#!/usr/bin/python
import os
from wsgiref.handlers import CGIHandler
from hello import app
os.environ['SERVER_NAME'] = '127.0.0.1'
os.environ['SERVER_PORT'] = '5000'
os.environ['REQUEST_METHOD'] = 'GET'
os.environ['PATH_INFO'] = ""
CGIHandler().run(app)
Both the files are placed in the /home/username/public_html/cgi-bin directory
The same cgi-bin has the directory named myenv - it's a virtualenv I have created. The virtualenv is active.
Now,
I navigate to the cgi-bin directory and run -
python hello.py
I get this :
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
So this is fine. Now I am running the myapp.cgi file:
python myapp.cgi
I get this :
Status: 301 MOVED PERMANENTLY
Content-Type: text/html; charset=utf-8
Content-Length: 251
Location: http://127.0.0.1:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: http://127.0.0.1:5000/. If not click the link.
How can I make this status as 200 OK,
Please suggest.
Thanks!

I had to make few changes in the .cgi file. Below is the final file.
import os
from wsgiref.handlers import CGIHandler
from hello import app
CGIHandler().run(app)
and added these lines in my hello.py file:
import os
import sys
sys.path.insert(0, '/home/username/public_html/cgi-bin/myenv/lib/python2.6/site-packages')
Refer this - https://medium.com/#mohdejazsiddiqui/deploy-flask-app-in-apache-shared-hosting-5b3c82c8fd5e

I think you have 2 big misunderstandings about how apache works with flask with the help of cgi.
Apache uses the system directorys for the python interpreter. You can in fact change the sys.path Like here descriped. But that is far from ideal.
you don't have to call python for your cgi file. The Server will do that when you did your config correctly
in the cgi doc of flask are some ways how you get the server to work with the cgi file.
Since you say you want it to upload at shared hosting writing a .htaccess file for your needs would be the most promesing way, since most of those services only allow you to work from your public dircectory. In this case you also have to use a shared hoster where python is on the server or be willed to install python with all the packages you need for you, since you can't install any packages by yourself.
You could try the changing of the interpreter path, but i have no experience if that would work on shared hosting.

Related

Unable to view flask app -- network error 404 on localhost

I see this issue posted alot...but no solutions thus far have worked for me (sorry about the repost).
PROBLEM
I'm trying to run flask on my windows10 machine, and am unable to load a simple hello.py without a 404 error.
DEBUGGER
The debugger is working for syntax errors (I can see the lines from hello.py file in my browser if I break the syntax in the file...but I'm getting no help on the 404 if the py file doesn't contain errors. The terminal also detects changes to the file it's supposed to load on the screen.
(I take it this means that the venv is set up properly, and the issue lies in the network handlers on windows..)
Things I've done
I've tried.
Disabling all the firewalls
Restarting the machine (countless times)
netstat -aon to confirm my ports are being used by another service.
Uninstalling and reinstalling python
Setting up new venvs on different drives on my machine
allowing all permissions in windows for all users and guests prior to creating the virtual environment.
installing xampp and setting up ports for apache => flask run --port:PORT
Uninstalling xampp
sitting and crying in the corner of the shower with water running on my face
Code for hello.py
'''
from flask import Flask
from werkzeug.debug import DebuggedApplication
app = Flask(__name__)
app.route('/')
def index():
return '<h1>hello world</h1>'
if __name__ =='__main__':
app.run(host='localhost', port=5000, debug=True)
'''
File Tree
_pycache_
Include
Lib
Scripts
hello.py
pip-selfcheck.json
pyvenv.cfg
You did not wrote the decorator for the index Function the right way.
This is a fixed Version who should work:
#app.route('/')
def index():
return '<h1>hello world</h1>'
The # symbol is needed to tell python that this function was decorated with the route.

Deploying a Django Application (Apache, Passenger, Virtualenv)

Im stuck in deploying my working Django Application on a production PLESK server.
The project can be started as a development server successfully by typing:
httpdocs# cd mysite
httpdocs/mysite# source myvenv/bin/activate
httpdocs/mysite# export LD_LIBRARY_PATH="/usr/local/lib"
httpdocs/mysite# python manage.py runserver <freyt.de>:8000
Then, if I point the browser to freyt.de:8000 I can see my app. Fine.
Right now, I'm trying to call my app by Passenger from Apache. When checking with "passenger-config restart-app" it seems to run, but when curl freyt.de it shows me html with 403 Forbidden. So, I assume my Django app is not started successfully.
This is my current folder structure:
I already adjusted some topics in PLESK as follows:
Apache Webserver: wsgi is activated
I created a Service Plan and subscribed it with my domain freyt.de
In the Service Plan under tab "Webserver" I added additional directives for HTTP as follows.
PassengerEnabled On
PassengerAppType wsgi
PassengerStartupFile passenger_wsgi.py
In the Service Plan under "Hosting Parameters" I enabled SSH access to the server shell: /bin/bash
For the "Domain" I set the Document root to "..httpdocs/public". Also I added in "Apache & nginx Settings" the same directives. (I also tried without, but dont seem to have an effect.)
Some details at Document Root:
I added .htaccess in public with again same directives (just for testing). No other files in public.
My passenger_wsgi.py contains, which seems to be ok:
import sys, os
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/mysite')
if sys.version < "2.7.9":
os.execl(cwd + "/mysite/myvenv/bin/python", "python3.6", *sys.argv)
sys.path.insert(0, cwd + '/mysite/myvenv/bin')
sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6')
#sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6/site-packages/django')
sys.path.insert(0, cwd + '/mysite/myvenv/lib/python3.6/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = "mysite.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
The file mysite/mysite/wsgi.py is untouched:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
Would be great, if someone could point me in the correct direction. I think its just a small mistake somewhere :-) Thanks in advance.

Python import from a virtual environment when run in apache

I am new in python. I am trying to deploy python code on apache server for i.e i have created flask api. So for apache i have installed XAMPP and changed my httpd.conf to execute python on apache. It works well!! Here is code example which is working
Code working:
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
print("Content-type: text/html\n")
print ("Hello Python Web Browser!! This is cool!!")
But when I tried to import that through 500 Error, Here is the code
#!C:\Users\test.lab\AppData\Local\Continuum\anaconda3\envs\myproject\python.exe
# enable debugging
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'testing'
if __name__ == '__main__':
app.run(debug = True)
flask is installed on my environment (myproject). When I run through command like python test.py and it works.
Flask has it's own development web server.
Using python myfile.py which will work properly as a webserver (no need for apache on development).
If you still want do deploy on Apache, Flask have some info on how to do so, docs: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
Special attention to this: http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/#creating-a-wsgi-file

Still having issues deploying flask app on Godaddy shared hosting

I've been trying now for some time to deploy my flask app on a Godaddy hosting server. I have done extensive searches online and followed them but I'm still having issues. Right now my app is just displaying as ordinary html so I'm having things like {{my_var}} displayed on the page. My flask app works locally and this is the folder structure;
myApp folder, which contains static folder for css,javascript, and images, templates folder for my html, and the myapp.py and forms.py files come under the myApp folder
On my hosting server my folder structure is currently this; $HOME/public_html which contains the index.html and base.html (index.html inherits from this file for the header and footers), $HOME/public_html/cgi-bin which contains myapp.cgi, myapp.py, and .htaccess files.
I've created a cgi file and made it executable which is saved in the public_html/cgi-bin folder. The file is also made executable with 755 permission. These are the contents;
#!/home/username/public_html/cgi-bin/flask_app/bin/python
from wsgiref.handlers import CGIHandler
from myapp import app
import os
import cgitb; cgitb.enable()
os.environ["SERVER_NAME"] = "127.0.0.1"
os.environ["SERVER_PORT"] = "4000"
os.environ["REQUEST_METHOD"] = "GET"
os.environ["SERVER_PROTOCOL"] = "http/1.1"
CGIHandler().run(app)
Note the shebang on my files is the path to my virtualenv where I have flask installed. The version of python is v2.7
I also have my main flask app (myapp.py which is also executable and with 755 permissions) file with the routes and the contents are as follows;
#!/home/username/public_html/cgi-bin/flask_app/bin/python
import os
import sys
sys.path.insert(0, '/home/aofadero/public_html/cgi-bin')#path to myapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run()
This file is also in my public_html/cgi-bin folder. I also have a .htaccess file which has the following content;
AddHandler cgi-script .cgi .py
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(/home/username/public_html/cgi-bin/myapp.cgi)
RewriteRule ^(.*)$ /home/username/public_html/cgi-bin/myapp.cgi/$1 [L]
Now this .htaccess file is currently in my public_html/cgi-bin folder because if I place it in public_html folder, I get a 500 error message. The only time I don't get the error is when the .htaccess file is in the cgi-bin folder. Some of the research I've done say to place it in the cgi-bin folder, others say in the public_html folder. I find that it only works for me when it's in the cgi-bin folder. If I do ./myapp.cgi I get the following error;
Status: 404 NOT FOUND
Content-Type: text/html
Content-Length: 233
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>...
Can anyone help me please because I've tried about everything I could on my own. Right now I'm just getting ordinary html and none of the flask components are showing. Thanks
I have similar problems. I understand that an index.htm file must be placed at public_html, but when you try to do render_template("index.htm"), Flask will look for this file in the templates folder. The rendering is not actually executed. The index.htm file will always be displayed on the browser as a default page. Have you been able to find the solution ?
You don't need to include the Python script in the public_html. If you go to the Cpanel main page and search for Python. From there, you can create a Python app which will let you direct your website to run the Python script.
Application root = path to the folder your python is stored. I stored mine in a Python folder in the root of the private html.
Application url = what URL should you need to put into the browser to get that script.
Application startup file = The name of your Python script.
Application Entry point = The callable object in your Python script (in your case, it would be app).
Please see the video here for a walkthrough of this process: https://www.youtube.com/watch?v=xFxL7Mvut6g&ab_channel=Hob-iZadeAdemEfendi

How do I set up a Python CGI server?

I'm running Python 3.2 on Windows. I want to run a simple CGI server on my machine for testing purposes. Here's what I've done so far:
I created a python program with the following code:
import http.server
import socketserver
PORT = 8000
Handler = http.server.CGIHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
In the same folder, I created "index.html", a simple HTML file. I then ran the program and went to http://localhost:8000/ in my web browser, and the page displayed successfully. Next I made a file called "hello.py" in the same directory, with the following code:
import cgi
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print()
print("""<html><body><p>Hello World!</p></body></html>""")
Now if I go to http://localhost:8000/hello.py, my web browser displays the full code above instead of just "Hello World!". How do I make python execute the CGI code before serving it?
Take a look at the docs for CGIHTTPRequestHandler, which describe how it works out which files are CGI scripts.
Though not officialy deprecated, the cgi module is a bit clunky to use; most folks these days are using something else (anything else!)
You can, for instance, use the wsgi interface to write your scripts in a way that can be easily and efficiently served in many http servers. To get you started, you can even use the builtin wsgiref handler.
def application(environ, start_response):
start_response([('content-type', 'text/html;charset=utf-8')])
return ['<html><body><p>Hello World!</p></body></html>'.encode('utf-8')]
And to serve it (possibly in the same file):
import wsgiref.simple_server
server = wsgiref.simple_server.make_server('', 8000, application)
server.serve_forever()
simplest way to start a cgi server for development is following:
create a base directory with all your html and other files
create a subdirectory named cgi-bin with all your cgi files
cd to the base directory
run python -m http.server --cgi -b 127.0.0.1 8000
Now you can connect to http://localhost:8000 and tst your html code with cgi scripts

Categories

Resources