logo
Hamburger_menu.svg

FOR DEVELOPERS

How to Use Python Language for Server Side Language

How to use Python language for server side language.

Python is one of the best programming languages to learn with applications in back-end web development, machine learning and statistics, scientific modeling, system operations, and several enterprise-specific software. Due to its English-like syntax, dynamic typing, and many libraries, it’s generally considered one of the more approachable programming languages.

This article will explore Python for server-side programming.

First, a quick look at what a server is.

Server (1).webp


Image source: sites.nd.edu

Server (1).webp


Image source: sites.nd.edu

The server is a client-server model in the infrastructure of the internet. Whenever a client browser visits a web page, it generates an HTTP request to the server holding the files required to manage a website. The server attends to the client’s request and processes it, responding with the necessary information to present the web page.

Server-side programming is classified into static and dynamic web servers. The former returns files as they are while the latter introduces databases and application servers.

Note: ‘File not found’ or 404, a ‘famous’ server error code that sometimes occurs when browsing the internet, is due to the server being unable to access some files.

Starting a web server in Python

Launching a Python web server takes only a few minutes as it’s quick and straightforward. Just one line of code gets the simplest local server running on a system. Through local testing, the system becomes the server to the client, which is the browser. The files are stored locally on the system.

To create a web server, you will need a Python HTTP server module that can be used as a static file server. For a dynamic web server, you will need a Python framework like Django or Flask.

The code:

python -m http.server

Type the code above into your command prompt or terminal, depending on your system. The ‘server started’ message will appear. And there you have it - your first Python webserver.

This is admittedly a simple code that does little more than open up a web server on your system’s default port of 8000. The port can be changed by specifying the port number at the end of the line.

python -m http.server 8080

Python code:

Python code.webp


Image source: by hacker.io

Python code.webp


Image source: by hacker.io

Dynamic web servers

Dynamic server-side websites deliver customized information in response to HTTP requests. They fulfill many operations such as retrieving data from a database, showing it on a page, validating user-entered data, saving it in a database, etc. The hugely popular Django is a completely featured dynamic server-side web framework written in Python.

Consider the number of products available in online retail stores and the number of posts written on social media. Displaying all of these using different static pages would be inefficient. So, instead of showing static templates (built using HTML, CSS, and JavaScript), it’s better to dynamically update the data displayed inside those templates when needed, such as when you want to view a different product in a retail store.

A brief overview of Django

Django is a high-level Python server-side web framework that allows the fast development of maintainable and protected websites. The open-source and free framework eliminates much of the hassle of web development. It also has a documented active community that provides many options at no cost.

Features of Django

- Secure: Django provides a framework that’s engineered to ‘do the right things’ to automatically protect websites. For example, it provides a secure way to manage user accounts and passwords.

Django can inspect if an entered password is correct by running it through a cryptographic hash function and resembling the output to the stored hash value. Due to this ‘one-way’ method, even if a stored hash value is compromised, it’s hard for an attacker to work out the original password. As it is, Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery.

- Versatile and complete: Django obeys the ‘batteries included’ philosophy by providing nearly everything that developers need to do things out-of-the-box. It helps create websites that include content management design systems, wikis to special networks, and news sites. It can also work in any client-side framework and delivers content in almost any format, such as HTML, JSON, XML, etc.

- Scalable: Django utilizes a component-based ‘shared-nothing’ architecture, which means that each part of the architecture is independent of the others. This allows it to be replaced or changed as required. The clear separation enables it to be scaled for increased traffic by adding hardware at any level, be it caching servers, database servers, or application servers.

- Maintainable and portable: Django code is written in such a way that it is reusable and maintainable. It follows the Don't Repeat Yourself (DRY) principle. There is no unnecessary duplication, which reduces the amount of code. It promotes grouping of related functionality into reusable ‘applications’, and at a lower level, groups related code into modules along with the line of the model-view-controller (MVC) pattern.

As Django is written in Python and runs on many platforms, you are not tied to any particular server platform. You can run applications on many flavors of Linux, Windows, and Mac OS X. What’s more, it’s well-supported by many web hosting providers that often provide specific infrastructure and documentation for hosting Django sites.

Django workflow

Traditional data-driven websites observe the following workflow:

  1. Web applications wait for the HTTP request from the web browser.
  2. Once the request receives the application, they work out what is needed based on the URL and possibly information in POST data or GET data. Then, depending on the requirements, they read or write data from a database or other tasks that need to satisfy the request.
  3. The applications return a response to the web browser in the form of HTML templates.

Common terminology

- URL: A mapper that maps the HTTP request from the client-side and redirects to the appropriate view based on the request URL. The mapper matches the particular patterns of strings and digits present in the URL.
- View: Acts as a request handler function that receives HTTP requests and returns HTTP responses.
- Models: Python objects that define the structure of an application's data and provide mechanisms to manage (add, modify, delete) and query records in the database.
- Template: A text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A view can dynamically create an HTML page using an HTML template, populating it with data from a model.

Python code to implement workflow of Django

Sending the request (urls.py)

Typically, the urls.py file is stored in the URL mapper.

url_patterns = [                             
    path("admit url"),                                  
    path('turing/<int:id>/', views.turing_detail, name='turing_detail'),                             
    path('catalogs/', include('catalogs.urls')),                            
    re_path(r'^([0-9]+)/$', views.best),                                             
]                             

url_patterns is a mapper that defines a list of mappings between the specific URL_pattern and the corresponding view function. If the URL matches a certain pattern, the associated view function will be called and pass the request.

Handling the request (views.py)

Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses.

from django.http import HttpResponse                        

def index_1(request):                           
    # Get an HttpRequest - the request parameter                               
    # perform operations using information from the request.                       
    # Return HttpResponse                         
    return HttpResponse(“Hello, welcome to turing.com”')      

Defining data models (models.py)

The data model helps Django web applications handle and query data through Python objects. Models give the structure of stored data, which includes field types, maximum size, default values, selection list options, text for documentation, etc.

from django.db import models                              

class Team(models.Model):                                  
    team_name = models.CharField(max_length=40)                             

    TEAM_LEVELS = (                           
        ('U09', 'Under 09s'),                             
        ('U10', 'Under 10s'),                           
        ('U11', 'Under 11s'),                        
        ... #list other team levels                            
    )                               
    team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default="U11")   

Rendering data (HTML templates)

Template systems authorize you to determine the structure of an output document by using placeholders for data that will be filled in when a page is generated. Templates are usually used to create HTML but can also create other types of documents.

##filename: best/templates/best/index.html

<!DOCTYPE html>                                        
<html lang="en">                                                       
<head>                                                             
 <meta charset="utf-8">                                                      
<title>Home page</title>                                                     
</head>                                           
<body>                                    
{% if youngest_teams %}                                              
<ul>                                             
{% for team in youngest_teams %}                                                       
<li>{{ team.team_name }}</li>                                               
{% endfor %}                                                    
</ul>                                                      
{% else %}                                               
<p>No teams are available.</p>                                        
{% endif %}                                   
</body>                                  
</html>

Many large-scale websites use server-side programming to display data dynamically whenever required. The biggest benefit of server-side code is that it permits you to tailor website content for various users. It has complete access to the server operating system, and can be written in different programming languages like Python, PHP, Ruby, C#, and JavaScript (NodeJS).

两个鬼故事结婚为什么电视剧起名网络八字生死帝尊bt天堂在线给宝宝取名起名大全测试起个霸气的名字公司起名的三大原则身上莫名起了红色疙瘩还很痒媚俗起名谐音大忌讳猪猪冒险岛阿富汗人口面积多少人口预备党员考察登记表起名五行缺金女孩ai换脸软件五行缺土起什么小名诺起名字 女孩名字敢想敢干起名算分网赌侠粤语11月4日是什么星座昆明起名大师太平洋电脑网_专业it门户网站徐州起名馆饺子馆怎样起名大将军司马懿之军师联盟小说排行榜前十名起点500分到530分的军校男宝宝姓邱起名字不问朝夕少年生前被连续抽血16次?多部门介入两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”淀粉肠小王子日销售额涨超10倍高中生被打伤下体休学 邯郸通报单亲妈妈陷入热恋 14岁儿子报警何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言张家界的山上“长”满了韩国人?男孩8年未见母亲被告知被遗忘中国拥有亿元资产的家庭达13.3万户19岁小伙救下5人后溺亡 多方发声315晚会后胖东来又人满为患了张立群任西安交通大学校长“重生之我在北大当嫡校长”男子被猫抓伤后确诊“猫抓病”测试车高速逃费 小米:已补缴周杰伦一审败诉网易网友洛杉矶偶遇贾玲今日春分倪萍分享减重40斤方法七年后宇文玥被薅头发捞上岸许家印被限制高消费萧美琴窜访捷克 外交部回应联合利华开始重组专访95后高颜值猪保姆胖东来员工每周单休无小长假男子被流浪猫绊倒 投喂者赔24万小米汽车超级工厂正式揭幕黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发当地回应沈阳致3死车祸车主疑毒驾恒大被罚41.75亿到底怎么缴妈妈回应孩子在校撞护栏坠楼外国人感慨凌晨的中国很安全杨倩无缘巴黎奥运校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变王树国卸任西安交大校长 师生送别手机成瘾是影响睡眠质量重要因素国产伟哥去年销售近13亿阿根廷将发行1万与2万面值的纸币兔狲“狲大娘”因病死亡遭遇山火的松茸之乡“开封王婆”爆火:促成四五十对奥巴马现身唐宁街 黑色着装引猜测考生莫言也上北大硕士复试名单了德国打算提及普京时仅用姓名天水麻辣烫把捣辣椒大爷累坏了

两个鬼故事 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化