Subdomain in Flask
In this article, We are going to learn about subdomains in Flask using Python. Firstly, we should know about the basics of Flask, domain name system(DNS) and subdomain. Many modules allow us to create a webpage in Python such as Django, bottle, flask etc. Flask is one of the web page frameworks or modules are written in Python. To learn more about Flask, visit this site Introduction and overview of Flask Framework and how to install it? Let’s learn about DNS and subdomains.
Domain Name System(DNS)
We, humans, prefer names instead of the numeric address(IP address). DNS is like a directory that holds the names of the different IP address. Technically speaking, Domain Name System (DNS) is a name resolution method that is used to resolve hostnames to IP addresses. It is used on TCP/IP networks and across the internet. For example, 126.96.36.199 is used to point the local computer address, localhost.
The subdomain is like a child domain to the parent domain. Subdomains are the domains that remain in the collections of the website. For example, practise.codespeedy.com and products.codespeedy.com are the subdomains of codespeedy.com/. Codespeedy is again a subdomain of com. I think, now you will understand what exactly the subdomain is. Here we are going to name our web page(URL) which is a sort of numeric address and include some subdomains in it.
Setting up a server in Flask
Firstly install these modules before coding. one is virtualenv and the other is Flask. you can install it by “pip install virtualenv” and “pip install flask”
Next, we create a simple web page with URL as localhost with default port number 5000.
from flask import Flask app = Flask(__name__) @app.route('/') def first_time_web(): return 'Welcome to my web page. This is my first try. Happy coding' if __name__ == '__main__': app.config['SERVER_NAME']='localhost:5000' app.run()
@app.route(‘/’) denotes that it is a base domain. I named the server here app.config[‘SERVER_NAME’]=’localhost:5000′
* Serving Flask app "monish" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://localhost:5000/ (Press CTRL+C to quit)
Check the link in the output in the browser.
Now adding subdomains in the page.
from flask import Flask app = Flask(__name__) @app.route('/') def first_time_web(): return 'Welcome to my web page. This is my first try. Happy coding' @app.route('/basic/') def basic(): return "This is the second page" @app.route('/', subdomain ='practice') def practice(): return "this is a subdomain of localhost" @app.route('/course/', subdomain ='practice') def blog(): return "blog taken by myself" if __name__ == '__main__': app.config['SERVER_NAME']='localhost:5000' app.run()
Now we can execute the code and check the link in the browser.
http://practice.localhost:5000/course/ or http://practice.localhost:5000/