The Wayback Machine - https://web.archive.org/web/20240913201432/https://www.geeksforgeeks.org/creating-a-proxy-webserver-in-python-set-2/
Open In App

Creating a Proxy Webserver in Python | Set 2

Last Updated : 19 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Creating a Proxy Webserver in Python – Set1 

In this tutorial, a few interesting features are added to make it more useful. 

  • Add blacklisting of domains. For Ex. google.com, facebook.com. Create a list of BLACKLIST_DOMAINS in our configuration dict. For now, just ignore/drop the requests received for blacklisted domains. (Ideally, we must respond with a forbidden response.) 
      
# Check if the host:port is blacklisted
for i in range(0, len(config['BLACKLIST_DOMAINS'])):
    if config['BLACKLIST_DOMAINS'][i] in url:
        conn.close()
return
  • To add host blocking: Say, you may need to allow connections from a particular subnet or connection for a particular person. To add this, create a list of all the allowed hosts. Since the hosts can be a subnet as well,  add regex for matching the IP addresses, specifically IPV4 addresses. “ IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1. Each part represents a group of 8 bits (octet) of the address.”
  • Using regex to match correct IP addresses: 
    • Create a new method, _ishostAllowed in  Server class, and use the fnmatch module to match regexes. Iterate through all the regexes and allow request if it matches any of them. If a client address is not found to be a part of any regex, then send a FORBIDDEN response. Again, for now, skip this response creation part.

Note: We would be creating a full-fledged custom webserver in upcoming tutorials, their creation of a createResponse function will be done to handle the generic response creation.

def _ishostAllowed(self, host):

    """ Check if host is allowed to access
        the content """
    for wildcard in config['HOST_ALLOWED']:
        if fnmatch.fnmatch(host, wildcard):
            return True
    return False

Default host match regex would be ‘*’ to match all the hosts. Though, regex of the form ‘192.168.*’ can also be used. The server currently processes requests but does not show any messages, so we are not aware of the state of the server. Its messages should be logged onto the console. For this purpose, use the logging module as it is thread-safe. (server is multi-threaded if you remember.)

Import module and setup its initial configuration.  

logging.basicConfig(level = logging.DEBUG,
format = '[%(CurrentTime)-10s] (%(ThreadName)-10s) %(message)s',)
  • Create a separate method that logs every message: Pass it as an argument, with additional data such as thread-name and current-time to keep track of the logs. Also, create a function that colorizes the logs so that they look pretty on STDOUT. 
    To achieve this, add a boolean in configuration, COLORED_LOGGING, and create a new function that colorizes every msg passed to it based on the LOG_LEVEL.
def log(self, log_level, client, msg):

    """ Log the messages to appropriate place """
    LoggerDict = {
       'CurrentTime' : strftime("%a, %d %b %Y %X", localtime()),
       'ThreadName' : threading.currentThread().getName()
    }
    if client == -1: # Main Thread
        formatedMSG = msg
    else: # Child threads or Request Threads
        formatedMSG = '{0}:{1} {2}'.format(client[0], client[1], msg)
    logging.debug('%s', utils.colorizeLog(config['COLORED_LOGGING'],
    log_level, formatedMSG), extra=LoggerDict)
  • Create a new module, ColorizePython.py:  It contains a  pycolors class that maintains a list of color codes. Separate this into another module in order to make code modular and to follow PEP8 standards.
# ColorizePython.py
class pycolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m' # End color
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

Module: 

import ColorizePython

Method: 

def colorizeLog(shouldColorize, log_level, msg):
    ## Higher is the log_level in the log()
    ## argument, the lower is its priority.
    colorize_log = {
    "NORMAL": ColorizePython.pycolors.ENDC,
    "WARNING": ColorizePython.pycolors.WARNING,
    "SUCCESS": ColorizePython.pycolors.OKGREEN,
    "FAIL": ColorizePython.pycolors.FAIL,
    "RESET": ColorizePython.pycolors.ENDC
    }

    if shouldColorize.lower() == "true":
        if log_level in colorize_log:
            return colorize_log[str(log_level)] + msg + colorize_log['RESET']
        return colorize_log["NORMAL"] + msg + colorize_log["RESET"]
    return msg 
  • Since the colorizeLog is not a function of a server-class, it is created as a separate module named utils.py which stores all the utility that makes code easier to understand and put this method there. Add appropriate log messages wherever required, especially whenever the state of the server changes.
  • Modify the shutdown method in the server to exit all the running threads before exiting the application. threading.enumerate() iterates over all the running threads, so we do not need to maintain a list of them. The behavior of the threading module is unexpected when we try to end the main_thread. The official documentation also states this:

“join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.” 

So, skip it appropriately. Here’s the code for the same. 

def shutdown(self, signum, frame):
    """ Handle the exiting server. Clean all traces """
    self.log("WARNING", -1, 'Shutting down gracefully...')
    main_thread = threading.currentThread() # Wait for all clients to exit
    for t in threading.enumerate():
        if t is main_thread:
            continue
            self.log("FAIL", -1, 'joining ' + t.getName())
        t.join()
        self.serverSocket.close()
    sys.exit(0)

If you have any comments/suggestions/queries then feel free to ask. 🙂 
 

About the Author:

Pinkesh Badjatiya hails from IIIT Hyderabad. He is a geek at heart with ample projects worth looking for. His project work can be seen here. 

If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.

 
 



Similar Reads

Creating a Proxy Webserver in Python | Set 1
Socket programming in python is very user friendly as compared to c. The programmer need not worry about minute details regarding sockets. In python, the user has more chance of focusing on the application layer rather than the network layer. In this tutorial we would be developing a simple multi-threaded proxy server capable of handling HTTP traff
5 min read
Python Tornado Webserver Simple Examples
Tornado is a robust, open-source web framework designed for building scalable and non-blocking web applications in Python. It was developed by FriendFeed (later acquired by Facebook) to handle long-lived network connections efficiently. Tornado is known for its high performance, simplicity, and asynchronous capabilities, making it an excellent choi
4 min read
How to Use Apache Webserver to Host a Website?
Apache is a powerful and widely used web server across the industry to host websites efficiently. In this guide, we will understand the usage of Apache web servers for hosting a website. PrerequisitesApache Web ServerAdministrative AccessSteps to use Apache webserver to host a website:Step 1: Basic ConfigurationOpen the Apache Configuration File Lo
2 min read
How to Install Node.js on a Webserver ?
Node.js is a powerful, lightweight, and efficient runtime for executing JavaScript code on the server side. It is particularly well-suited for building scalable network applications. Installing Node.js on a web server enables developers to run server-side JavaScript, host web applications, and serve dynamic content. This article provides a step-by-
2 min read
Creating multiple user types and using proxy models in Python Django
In this article, we will understand the concept of the proxy model and the implementation of multiple user types depending on the requirements of your application in Django. What is the Proxy model in Django? An inherited proxy model can have a few extra functionalities, methods, and different behaviors than the parent model as defined by the creat
9 min read
Proxy Design Pattern for Object Communication in Python
Memory and time are the two main challenges while working with large objects. So, it is important to reuse these objects to generate new references rather than creating them on every new request. And most importantly, memory must be released after all sections of code have completed working on it. A proxy design pattern is the best possible way to
4 min read
JavaScript Proxy() Constructor
JavaScript proxy() constructor is used to return the proxy constructor function for the object(e.g. property lookup, assignment, enumeration, function invocation, etc). Syntax: let p = new Proxy(target, handler); Parameter: The proxy object accept two parameters as mentioned above and described below: target: A target object (can be any sort of obj
2 min read
jQuery | $.proxy() Method
The $.proxy() Method in jQuery accepts an existing function and returns a new one with a particular context. Generally, it is used for attaching events to an element where the context is pointing back to a different object. Syntax: $(selector).proxy(function, context) $(selector).proxy(context, name) Parameter: This method accepts three parameters
2 min read
HTTP headers | Proxy-Authenticate
The HTTP Proxy-Authenticate is a response header gives access to a resource file by defining an authorization method. It allows the proxy server to transmit the request further by authenticating it. This header is sent along with 407 Proxy Authentication Required which indicates the inability to complete a request due to the lack of proper authoriz
1 min read
HTTP headers | Proxy-Authorization
The HTTP Proxy_Authorization header is a request type of header. This header contains the credentials to authenticate between the user agent and the user-specified server. When the server responded with 407 proxy Authentication Required status that brings the authentication between the user agent and the server. Syntax: Proxy-Authorization: <typ
1 min read
PyQt5 QCalendarWidget - Setting Focus Proxy
In this article we will see how we can set the focus proxy to the QCalendarWidget. Focus proxy is the setting focus to calendar indirectly i.e by setting focus to the child of it. For example, some widgets can "have focus", but create a child widget, such as QLineEdit, to actually handle the focus. In this case, the widget can set the line edit to
2 min read
PyQt5 QCalendarWidget - Getting Focus Proxy
In this article we will see how we can get the focus proxy to the QCalendarWidget. Focus proxy is the setting focus to calendar indirectly i.e by setting focus to the child of it. For example some widgets can "have focus", but create a child widget, such as QLineEdit, to actually handle the focus. In this case, the widget can set the line edit to b
2 min read
PyQt5 QCalendarWidget - Getting Graphics Proxy Widget Property
In this article we will see how we can get the graphic proxy widget of the QCalendarWidget. Graphics proxy widget returns the proxy widget for the corresponding embedded widget in a graphics view; otherwise returns None. In order to do this we will use graphicsProxyWidget method with the QCalendarWidget object. Syntax : calendar.graphicsProxyWidget
2 min read
JavaScript Proxy/handler Reference
JavaScript Proxy Object is used to define the custom behavior of fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc). Syntax: const p = new Proxy(target, { Proxy method: function(target, thisArg, argumentsList) { } }); Example: Below examples illustrate the handler.apply() method in JavaScript: C/C++ Cod
2 min read
How to create proxy server on Heroku in Node.js ?
The following approach covers how to create a proxy server on Heroku using NodeJS. Heroku is a cloud application platform that is used as PaaS (Platform as a service) to build, operate and run applications on their cloud. Prerequisites: To create a proxy server, you will need the following to be installed on your computer: Install Heroku CLI.Instal
2 min read
Feeding JSON Data to Kafka Topic Using Rest Proxy
This POC describes the procedure of feeding JSON format data to a Kafka Topic using Kafka REST Proxy, that which provides a RESTful interface to a Kafka cluster. Prerequisites: Before you start this procedure, ensure that : Administrative access to running Kafka VM and that VM must have connectivity as described in the loading Prerequisites.Identif
4 min read
JavaScript Proxy revocable() Method
The Proxy.revocable() method is a built-in method in JavaScript that creates a revocable Proxy object. This method returns an object that contains two properties: proxy and revoke. The proxy property is a Proxy object, which is used to intercept and handle operations on another object. The revoke property is a function that can be called to revoke
2 min read
How to Create Props Proxy for HOC Components ?
We will delve into the process of creating a props proxy for higher-order components (HOCs). This approach enables the addition of props to wrapped components before rendering, proving useful in various scenarios such as logging, modifying data passed to components, and managing authentication in diverse applications. Prerequisites:React JS introdu
2 min read
How Proxy Backend Server using React.js ?
When building a web application with React.js, you may need to request a backend server. However, if the backend server does not allow Cross-Origin Resource Sharing (CORS), you may encounter an error when requesting from the frontend application. In this case, you can use the proxy server to forward requests from the front-end application to the ba
3 min read
What is Zed Attack Proxy?
Zed Attack Proxy is an open-source security software written in Java programming language and released in 2010. It is used to scan web applications and find vulnerabilities in it. It was started as a small project by the Open Web Application Security Project (OWASP) and now it is the most active project maintained by thousands of individuals around
3 min read
What is the use of Proxy Object in JavaScript ?
In JavaScript, the Proxy object acts as a assistant for objects, allowing fine-grained control over their behavior when accessing or modifying properties. With Proxy, you can customize an object's behavior, enforcing specific rules or implementing special actions. For instance, you might employ a Proxy to ensure that when modifying a person's age p
2 min read
How To Use Apache as a Reverse-Proxy with mod_proxy on Ubuntu 20.04?
Reverse proxy is a server between client and backend servers, it forwards the client requests to the available backend server. Apache is a popular web server proxy using the mod_proxy module. In this article, we will understand how to use Apache as a reverse proxy with mod_proxy. PrerequisitesA server running Ubuntu 20.04.Apache is installed on you
3 min read
Getting Git To Work With a Proxy Server
When working in a networked environment, particularly in corporate settings, you may find yourself behind a proxy server. This can sometimes interfere with your ability to use Git. Configuring Git to work with a proxy server ensures seamless operation and uninterrupted access to repositories. This article will guide you through the steps to configu
4 min read
JavaScript Proxy/Handler
JavaScript Proxy is an object which intercepts another object and resists the fundamental operations on it. This object is mostly used when we want to hide information about one object from unauthorized access. A Proxy consists of two parts which are its target and handler. A target is a JavaScript object on which the proxy is applied and the handl
3 min read
How to Build a Node.js Proxy Server ?
A proxy server acts as an intermediary between a client and other servers. It can be used for various purposes, including load balancing, security, and caching. In the context of web development, a proxy server forwards requests from clients to other servers, fetches responses, and sends them back to the clients. In this article, we will create a N
4 min read
How to Configure Proxy in Vite?
Vite is a popular build tool for modern web libraries and frameworks like React and Vue. It provides features such as dependency resolving, pre-bundling, hot module replacement, typescript support. Using vite you can configure a proxy to handle requests to different backends or APIs during development. It helps bypass CORS issues and manage API req
3 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Sites like Hot Frameworks assess the popularity of a
3 min read
Creating views on Pandas DataFrame | Set - 2
Prerequisite: Creating views on Pandas DataFrame | Set - 1 Many times while doing data analysis we are dealing with a large data set has a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let's see how we can create views on the D
2 min read
Practice Tags :