Allow urls containing "www." on openshift hosted website - python

I have a (very) simple flask app hosted on open-shift.
It has one route:
#app.route('/')
def display_content():
return render_template("content.html.jnj2")
and a simple wsgi file (as described in the open-shift flask setup tutorial):
from wsgiref.simple_server import make_server
httpd = make_server('localhost', 8051, application)
httpd.serve_forever()
This works fine when I navigate to "myappname-mydomain.rhcloud.com", but gives an "ERR_NAME_NOT_RESOLVED" when I navigate to "www.myappname-mydomain.rhcloud.com".
I've done some googling etc, can't see anyone else with a similar problem.. I'm not aware of having changed any open-shift settings or anything.

Your app-domain.rhcloud.com address that is provided by OpenShift does NOT include a cname for www.app-domain.rhcloud.com, that's why it's not working. You can use your app-domain.rhcloud.com, or you can map your own alias like example.com or www.example.com using this guide: https://developers.openshift.com/en/managing-domains-ssl.html#using-a-custom-domain

Related

Python Flask app route is not working well

I tried to find a solution for my problem in other questions but I couldn't.
I downloaded the python flask and made my first flask app and it ran fine.
Here is the code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
When I ran my second file where I had added an app.route ("/ david") and followed the same procedure again, refreshed it and nothing changed.
That is to say, I was going to / david and I get an URL error
Here is my second file
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
#app.route("/david")
def david():
return "Hello, David!"
I tried the same with other files which have some added routes and the result is the same as the first file
Thanks for your answers, I hope to solve my problem.
You did not run the app. What you did is just create a structure for flask, but did not start the server.
Just add:
app.run()
To the bottom of the file and it will work. It will with start the flask server at http://localhost:5000.
By default, flask runs on port 5000.
It can be changed by:
app.run(host="0.0.0.0", port=xxxx)
0.0.0.0 means it accepts request from anywhere on the port specified.
Make sure you have all the permissions and nothing else is running if you want it to run on port 80.
Hope this helps. Good luck.
I had the same issue. Try first by restarting your IDE; this worked for me. If that doesn't work, try clearing your ports for Windows:
Open Task manager
Click on the “Processe” tab
Enable the "PID" column: View -> Select Columns -> Check the box for PID
Find the PID (in your case, 5000 - flask default port) and click “END PROCESS"

Docker - Can't get user webcam: getUserMedia() no longer works on insecure origins

WHAT WORKS
I created a simple Web Application in Flask that takes care of operating a simple return render_template("index.html") when the root node is accessed by a Web Browser.
# app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80)
The index.html is a simple page that uses tracking.js in order to get the user webcam and track his/her face in the live video stream.
Opening cmd and typing python app.py results in Running on http://127.0.0.1:80/
Accessing the above mentioned URL results in the correct display of the page, that asks me for permission to use the camera, opens it and correctly tracks my face in the live video feed. So it's all working fine till here.
WHAT DOES NOT WORKS
The problem I'm experiencing arises when I dockerize my application using Docker. docker-machine ip is 192.168.99.100
Opening cmd and typing: docker run -p 4000:80 my_face_track_app results in: Running on http://0.0.0.0:80/
Accessing 192.168.99.100:4000 results in the correct display of index.html but I am not asked anymore for permission on the camera and inspecting the JS console I read the following exception:
getUserMedia() no longer works on insecure origins
Here the full error log:
I know the error is telling me I'm not serving the page in HTTPS.
Has anyone else encountered this problem?
What would be the proper solution to the issue or a possible walkaround?
Any help will be highly appreciated, thank you a lot in advance
WHAT I HAVE TRIED TO DO IN ORDER TO SOLVE THE PROBLEM
Since an HTTPS serving of the page is needed in order for JS to execute the function getUserMedia() I tought about serving my Flask application with an SSL certificate by modifying app.py like this:
# app.py
from flask import Flask, render_template
import OpenSSL
app = Flask(__name__)
#app.route("/")
def show_index():
return render_template("index.html")
if __name__ == "__main__":
app.run(port=80, ssl_context="adhoc")
I then dockerized the app building a new image. Typing:
docker run -p 443:80 facetrackapphttps
Results in
Running on https://127.0.0.1:80
So yeah, here HTTPS is ON: the problem is that the port 80 of the HTTPS Flask App is mapped to the port 443 of the docker-machine ip 192.168.99.100.
Trying to access 192.168.99.100:443 does not work and nothing is shown.
Does anybody have an idea about how to do this?
If your application is bound to 127.0.0.1 inside the container, you're not going to be able to access it from your host. According to the flask docs, flask will bind to 127.0.0.1 by default.
You'll need to modify your service so that it binds to 0.0.0.0 inside the container:
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, ssl_context="adhoc")

How can I have my flask-app run on my sites subdomain?

For example, I want to run flask-app on http://api.domain.com . However, I have no idea how to do this and the flask documentation serves no help. I am using a shared namecheap web server via SSH to run python. I have ports 8080, 8181 and 8282 open.
Server-sided code:
from flask import Flask
from flask import Blueprint
app = Flask(__name__)
app.config['SERVER_NAME'] = 'domain.com'
#app.route('/status')
def status():
return 'Status : Online'
bp = Blueprint('subdomain', __name__, subdomain="api")
app.register_blueprint(bp)
if __name__ == '__main__':
app.run(host=app.config["SERVER_NAME"],port=8181,debug=True)
When I visit http://www.api.domain.com/status , it returns a 404 error.
Nothing displays on the SSH console.
Any help if very much appreciated.
First things first:
http (i.e. a web server without a SSL certificate) is insecure. You should set up a certificate and always use port 443 to the outside.
Then, on namecheap, you need to define a CNAME entry to point to the subdomain.
In Namecheap, click domain -> Manage, then Advanced DNS
Create a new record, select CNAME as the Type, and enter the subdomain name (just the top level) as the HOST, then the IP where you server is as the value (TTL (time to live) is the time it takes to change when you want to change it next time, 1, 10min is useful to debug stuff, but DNS may not honor that anyways...)
Wait a few minutes, and you should be able to reach your server at the subdomain name.
Now, if you use the same IP as a webserver for example, but a different port, that is basically not gonna do what you want. The DNS will forward subdomain traffic to your (same) server IP, so if your webserver is on port 443, you will also reach it with https://api.domain.com. If your API uses port 8080 or 8081, you will need to always specify the port to actually reach the API server at the subdomain (i.e api.domain.com:8080 ).
The DNS merely forwards the subdomain name to the IP you tell it to.
I solved this using the tornado in Python. I already answered this question and it's working fine
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(int(5000),address="ip_address_of_your_server_machine")
IOLoop.instance().start()
Now you can access this page like www.example.com:5000
Actually Flask is not meant to run a server by itself, it's only for debugging, if you want to run an web app you should run behind a Apache or Nginx with some wsgi, here is an simple example on Ubuntu 18.04 LTS:
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04

arduino yun uhttpd flask setup

I'm trying to set up python and flask on the arduino yun. I've managed to run python files via the /etc/config/uhttpd configuration file:
...
list interpreter ".py=/usr/bin/python"
...
The default path for the website's root is: /www in which I've placed a soft link (apps) to the sd card. So now I can run python programs: http://[ip arduino]/apps/helloworld.py
And when I make my first helloflask.py program and run that via python helloflask.py I can see the result at: http://[ip arduino]:5000
But now I want to configure the uhttpd mini webserver (which is capable to exchange information via CGI) to use the flask setup. The URI: http://flask.pocoo.org/docs/deploying/cgi/#server-setup shows some instructions... but I just don't get it. I've made a directory ../apps/uno in which I've placed a __init__.py file with the following content:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "He Flask!"
In the apps dir I've put a file: cgi.py with this content:
from wsgiref.handlers import CGIHandler
from uno import app
CGIHandler().run(app)
Now I when I browse: http://[ip arduino]/cgi.py get a server error occured, contact the administrator (I think this is the CGI interface from uhttpd).
I just don't grasp the CGI configuration for Flask/uhttpd
I looked into this too and got a little further, I was able to setup a simple hello world but once I tried to do something non-trivial I ran into a big issue that uhttpd doesn't support URL rewriting/aliasing. This means your flask app can only be served at the URL of its .py file instead of at a root like http:// (arduino IP) /flaskapp/. None of the routes inside the app will be visible and makes the whole thing unusable.
However, instead of trying to force flask into uhttpd I had great success running the built in server that flask provides. Take a look at this guide I wrote up that uses flask to serve data from a Yun: https://learn.adafruit.com/smart-measuring-cup/overview
The thing to do is add a call to app.run when the script is run, for example make your flask app look like:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello Flask!"
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, threaded=True)
Then log in to the Yun and run the script using python. Flask's built in server should start serving the app on http:// (arduino IP) :5000/. Make sure to include the host='0.0.0.0' as it's required to listen on the Yun's external network interface. You probably also want debug=True so there are better error messages (and live reloading of the server when the code changes), and I found threaded=True helps because the default server only handles one connection at a time. The Yun is a relatively slow processor so don't expect to service a lot of concurrent requests, however it's quite capable for providing a simple REST API or web application for a few users.
If you want this server to always run on bootup, edit the /etc/rc.local file to include a call to python and your script.

How can I use a single server to deploy multiple WSGI apps on multiple domains?

Hypothetical
I've got a Linux VPS server named myserver, mounted at myserver.com.
On this server I have two Flask WSGI apps app-one and app-two.
I'd like to deploy these two apps on myserver, but I want them mounted on the domains app-one.com and app-two.com.
The apps have no external dependencies (no databases, caches, etc). They're stand-alone, single-file apps.
I do not have Apache, NGinX or any other webserver software installed; just Python, Flask and two WSGI apps.
I have Python/Flask experience, but I don't have a lot of experience with WSGI deployment or multiple-domain work. Basic instructions and/or reading material appreciated.
Question / TL;DR
How can I use a server mounted at one domain to deploy two WSGI apps to two domains? Do I need to install software especially for this case, or is it just a matter of pointing the apps at my chosen domains?
Thank you for any and all advice.
Once you have DNS set up to point both app-one.com and app-two.com to myserver.com's IP address then you need to set up something to route requests coming in on port 80 (or 443 if you are going to use SSL) to each of your apps. This is normally done with virtual hosts in Apache or nginx.
If you need to run both applications in the same Python process (whether you are using a non-Python webserver as your application container or not) then you will need to dispatch to each of your apps by hand:
from werkzeug.exceptions import NotImplemented
from werkzeug.wsgi import get_host
class DomainDispatcher(object):
"""Simple domain dispatch"""
def __init__(self, domain_handlers, default_handler=None):
self.domain_handlers = domain_handlers
self.default_handler = domain_handlers.get("default", default_handler)
if self.default_handler is None:
self.default_handler = NotImplemented()
def __call__(self, environ, start_response):
host = get_host(environ)
handler = self.domain_handlers.get(host, self.default_handler)
return handler(environ, start_response)
An example of usage:
from app_one import app as app1
from app_two import app as app2
from domain_dispatcher import DomainDispatcher
dispatcher = DomainDispatcher({'app-one.com': app1, 'app-two.com': app2})
if __name__ == '__main__':
# Wrap dispatcher in a WSGI container
# such as CherryPy

Categories