Local server with python

Create a Quick Local Web Server with Python and Ngrok

One of the nice things about starting a new job is that you have to setup all of your development tools and environments from scratch. And some of the things you thought you’d never forget stubbornly hide behind the memories that are much easier to recall. Such was the case for me recently. On a machine that was only a few weeks old, I needed to make an HTML file quickly accessible to the outside world. I had done this dozens of times before, but for the life of me, I could not remember the exact tools I needed to get this job done. Then, after much searching, the fog cleared. All I needed was to run a single Python command to fire up a local web server. Then, using a tool called ngrok I could make that server accessible to the world. This blog post is more of an insurance policy against my faulty memory, so I can easily remind myself of these things in the future. However, you are more than welcome to continue reading if this sounds interesting to you. First, let’s get the Python web server running on port 8000.

Читайте также:  Fatal error allowed memory size php mysql

Python

A super quick way to fire up a web server, with virtually no configuration (especially if you’re on macOS) is to use Python’s SimpleHttpServer. In Python 2.7 (which is the default version that comes with macOS) the server is started by running python -m SimpleHTTPServer 8000 . In Python 3 this can be done by running python -m http.server 8000 . With this command, the SimpleHTTPServer will serve up the contents of the current directory on port 8000. Any port can be specified here, but make sure it’s one that is not currently in use. The contents can be accessed locally by pointing your browser to http://localhost:8000/. Now that the simple web server is running, it’s time to configure ngrok to make this server accessible by the Internet at large.

ngrok

  • Download ngrok from the ngrok Download Page.
  • Extract the ngrok executable and put it somewhere that makes sense to you. I put it in /Applications/Utilities .
  • To get the ngrok executable into PATH so that it’s executable from anywhere on your system, create a symlink in /usr/local/bin/ that points to where ever ngrok is saved. If it’s in the Utilities directory, as mentioned above, the symlink command would look like this ln -s /Application/Utilities/ngrok /usr/local/bin/ngrok
  • Go the the directory where SimpleHTTPServer is running and run the following command ngrok http 8000

The ngrok output then shows the following:

Screenshot of ngrok

The important piece you’re looking for are the values for Forwarding . The local web server will now be visible at the x.ngrok.io domains. As requests are made to this tunnel, the results are logged in the Connections section of the ngrok CLI. For the free version of ngrok, this session will last for 8 hours. When the ngrok process expires, or is restarted, the subdomain value in the address will change. If you’re looking for a consistent address, I believe you can purchase a license from ngrok.

Читайте также:  Php ini memory limit 1024m

Now with these two simple tools you can spin up publicly accessible web servers to your heart’s content.

Источник

How do you set up a local testing server?

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

Prerequisites: You need to first know how the Internet works, and what a Web server is.
Objective: You will learn how to set up a local testing server.

Local files vs. remote files

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double-clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open… and navigating to the HTML file. There are many ways to achieve this.

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https:// , to show that the file has been received via HTTP.

The problem with testing local files

Some examples won’t run if you open them as local files. This can be due to a variety of reasons, the most likely being:

  • They feature asynchronous requests. Some browsers (including Chrome) will not run async requests (see Fetching data from the server) if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).
  • They feature a server-side language. Server-side languages (such as PHP or Python) require a special server to interpret the code and deliver the results.
  • They include other files. Browsers commonly treat requests to load resources using the file:// schema as cross-origin requests. So if you load a local file that includes other local files, this may trigger a CORS error.

Running a simple local HTTP server

To get around the problem of async requests, we need to test such examples by running them through a local web server.

Using an extension in your code editor

If you only need HTML, CSS and JavaScript, and no server-side language, the easiest way may be to check for extensions in your code editor. As well as automating installation and set-up for your local HTTP server, they also integrate nicely with your code editors. Testing local files in an HTTP server may be one click away.

For VSCode, you can check the following free extension:

Using Python

Another way to achieve this is to use Python’s http.server module.

Note: Older versions of Python (up to version 2.7) provided a similar module named SimpleHTTPServer . If you are using Python 2.x, you can follow this guide by replacing all uses of http.server with SimpleHTTPServer . However, we recommend you use the latest version of Python.

  1. Install Python. If you are using Linux or macOS, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:
    • Go to python.org
    • Under the Download section, click the link for Python «3.xxx».
    • At the bottom of the page, click the Windows Installer link to download the installer file.
    • When it has downloaded, run it.
    • On the first installer page, make sure you check the «Add Python 3.xxx to PATH» checkbox.
    • Click Install, then click Close when the installation has finished.
  2. Open your command prompt (Windows) / terminal (macOS/ Linux). To check if Python is installed, enter the following command:
-V # If the above fails, try: python3 -V # Or, if the "py" command is available, try: py -V 
# include the directory name to enter it, for example cd Desktop # use two dots to jump up one directory level if you need to cd .. 
# If Python version returned above is 3.X # On Windows, try "python -m http.server" or "py -3 -m http.server" python3 -m http.server # If Python version returned above is 2.X python -m SimpleHTTPServer 

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python3 -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800 .

Running server-side languages locally

Python’s http.server (or SimpleHTTPServer for Python 2) module is useful, but it is merely a static file server; it doesn’t know how to run code written in languages such as Python, PHP or JavaScript. To handle them, you’ll need something more — exactly what you’ll need depends on the server-side language you are trying to run. Here are a few examples:

  • To run Python server-side code, you’ll need to use a Python web framework. There are many popular Python web frameworks, such as Django (a guide is available), Flask, and Pyramid.
  • To run Node.js (JavaScript) server-side code, you’ll need to use raw node or a framework built on top of it. Express is a good choice — see Express Web Framework (Node.js/JavaScript).
  • To run PHP server-side code, launch PHP’s built-in development server:
cd path/to/your/php/code php -S localhost:8000 

Found a content problem with this page?

This page was last modified on Jul 3, 2023 by MDN contributors.

Источник

Пишем простой сервер на Python

Ну, начнем как и везде с определений, берите тетрадь и ручку сейчас начнется нудятина. Чтобы мы cмогли написать свой сервер, нужно для начала понимать как он вообще работает, ловите определение:

Сервер – это программное обеспечение, которое ожидает запросов клиентов и обслуживает или обрабатывает их соответственно.

Если объяснять это своими словами, представьте фургон с хот-догами(сервер), проголодавшись, вы(клиент) подходите и говорите повару, что вы хотите заказать(запрос), после чего повар обрабатывает, что вы ему сказали и начинает готовить, в конечном итоге вы получаете свой хот-дог(результат) и сытый радуетесь жизни. Для наглядности посмотри схему.

Околопрактика

Для написания сервера мы будем использовать Python и модуль Socket.

Socket позволяет нам общаться с сервером с помощью сокетов. Весь код я постараюсь пояснять, дабы ты мой дорогой читатель все понял. В конце статьи будет готовый код.

Создайте два файла в одной директории:

Практика

Пишем код для серверной части, так что открывайте файл socket_server.py.

Начнем с импорта модуля и создания TCP-сокета:

Далее весь код будет с комментариями:

s.bind(('localhost', 3030)) # Привязываем серверный сокет к localhost и 3030 порту. s.listen(1) # Начинаем прослушивать входящие соединения conn, addr = s.accept() # Метод который принимает входящее соединение.

Добавим вечный цикл, который будет считывать данные с клиентской части, и отправлять их обратно.

while True: # Создаем вечный цикл. data = conn.recv(1024) # Получаем данные из сокета. if not data: break conn.sendall(data) # Отправляем данные в сокет. print(data.decode('utf-8')) # Выводим информацию на печать. conn.close()

Переходим к клиентской части, весь код теперь пишем в файле socket_client.py.

Начало у клиентской части такое-же как и у серверной.

import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Далее подключимся к нашему серверу и отправим сообщение «Hello. Habr!».

s.connect(('localhost', 3030)) # Подключаемся к нашему серверу. s.sendall('Hello, Habr!'.encode('utf-8')) # Отправляем фразу. data = s.recv(1024) #Получаем данные из сокета. s.close()

Слева сервер, справа клиент

Заключение

Вот мы с вами и написали свой первый сервер, рад был стараться для вас, ниже будет готовый код.

socket_server.py:

import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 3030)) # Привязываем серверный сокет к localhost и 3030 порту. s.listen(1) # Начинаем прослушивать входящие соединения. conn, addr = s.accept() # Метод который принимает входящее соединение. while True: data = conn.recv(1024) # Получаем данные из сокета. if not data: break conn.sendall(data) # Отправляем данные в сокет. print(data.decode('utf-8')) conn.close()

socket_client.py:

import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('localhost', 3030)) # Подключаемся к нашему серверу. s.sendall('Hello, Habr!'.encode('utf-8')) # Отправляем фразу. data = s.recv(1024) #Получаем данные из сокета. s.close()

Источник

Оцените статью