首页服务器python搭建web服务器 python 怎么搭建简单的web服务器

python搭建web服务器 python 怎么搭建简单的web服务器

编程之家2023-10-24108次浏览

很多朋友对于python搭建web服务器和python 怎么搭建简单的web服务器不太懂,今天就由小编来为大家分享,希望可以帮助到大家,下面一起来看看吧!

python搭建web服务器 python 怎么搭建简单的web服务器

如何用python搭建一个最简单的Web服务器

用Python建立最简单的web服务器

利用Python自带的包可以建立简单的web服务器。在DOS里cd到准备做服务器根目录的路径下,输入命令:

python-mWeb服务器模块[端口号,默认8000]

例如:

python-m SimpleHTTPServer 8080

然后就可以在浏览器中输入

python搭建web服务器 python 怎么搭建简单的web服务器

http://localhost:端口号/路径

来访问服务器资源。

例如:

http://localhost:8080/index.htm(当然index.htm文件得自己创建)

其他机器也可以通过服务器的IP地址来访问。

这里的“Web服务器模块”有如下三种:

python搭建web服务器 python 怎么搭建简单的web服务器

BaseHTTPServer:提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler。

SimpleHTTPServer:包含执行GET和HEAD请求的SimpleHTTPRequestHandler类。

CGIHTTPServer:包含处理POST请求和执行CGIHTTPRequestHandler类。

python 怎么搭建简单的web服务器

利用Python自带的包可以建立简单的web服务器。在DOS里cd到准备做服务器根目录的路径下,输入命令:\x0d\x0apython-m Web服务器模块 [端口号,默认8000]\x0d\x0a例如:\x0d\x0apython-m SimpleHTTPServer 8080\x0d\x0a然后就可以在浏览器中输入\x0d\x0ah ttp://loca lhost:端口号/路径\x0d\x0a来访问服务器资源。 \x0d\x0a例如:\x0d\x0ah ttp://local host:808 0/index.h tm(当然index.htm文件得自己创建)\x0d\x0a其他机器也可以通过服务器的IP地址来访问。\x0d\x0a\x0d\x0a这里的“Web服务器模块”有如下三种:\x0d\x0a\x0d\x0aBaseHTTPServer:提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler。\x0d\x0aSimpleHTTPServer:包含执行GET和HEAD请求的SimpleHTTPRequestHandler类。\x0d\x0aCGIHTTPServer:包含处理POST请求和执行CGIHTTPRequestHandler类。

教你如何搭建简易网站:python开发web服务器

Python中有数不清的Web框架,从基本的微小架构到完整的架构,它们自有各自的优点。那么你准备使用它来做一些web开发,但在探讨细节之前,让我们从头开始。

目标

用已有的丰富图片资源建一个看图网站

条件开发语言:python3

库:flask:一个开源的python web服务器框架

jinja2:flask默认的模板引擎

编辑器:推荐pycharm

一个最简单的web服务器python给我们提供了一个接口:WSGI:Web Server Gateway Interface

它只要求Web开发者实现一个函数,就可以响应HTTP请求。而不用触到TCP连接、HTTP原始请求和响应格式。

下面实例一个最简单的web应用:

# hello.pydef application(environ, start_response):

start_response('200 OK', [('Content-Type','text/html')]) return [b'<h1>Hello, Python web!</h1>']# server.py#从wsgiref模块导入:from wsgiref.simple_server import make_server#导入我们自己编写的application函数:from hello import application#创建一个服务器,IP地址为空,端口是8000,处理函数是application:httpd= make_server('', 8000, application)

print('Serving HTTP on port 8000...')#开始监听HTTP请求:httpd.serve_forever()environ:一个包含所有HTTP请求信息的dict对象;

start_response:一个发送HTTP响应的函数。

将两个脚本放在同一目录下,运行server.py,访问 http://127.0.0.1:8000就能看到效果了。

处理url其实web应用,就是对不同url的处理。

我们将hello.py进行修改

def application(environ, start_response):

method= environ['REQUEST_METHOD']

path= environ['PATH_INFO'] if method=='GET' and path=='/': return handle_home(environ, start_response) if method=='POST' and path='/signin': return handle_signin(environ, start_response)

...这样就会处理两个url,’/’和’/signin’

当然你可以这么一直写下去?如果你不嫌累的话。

使用模板既然上面的方法太累太慢,那我们学点高级的:

flask

看代码

from flask import Flaskfrom flask import request

app= Flask(__name__)@app.route('/', methods=['GET','POST'])def home():

return'<h1>Home</h1>'@app.route('/signin', methods=['GET'])def signin_form():

return'''<form action="/signin" method="post">

<p><input name="username"></p>

<p><input name="password" type="password"></p>

<p><button type="submit">Sign In</button></p>

</form>'''@app.route('/signin', methods=['POST'])def signin():

#需要从request对象读取表单内容:

if request.form['username']=='admin' and request.form['password']=='password': return'<h3>Hello, admin!</h3>'

return'<h3>Bad username or password.</h3>'if __name__=='__main__':

app.run()注意,这个是单文件。

来分析这个脚本:

Flask通过Python的装饰器在内部自动地把URL和函数给关联起来。

启动运行后,我们访问

‘/’,看到的页面是一个“HOME”单词

‘/signin’,此刻是通过GET访问,看到的是一个表单,填写’admin’和’password’,点击登录——>

‘/signin’,此刻是通过POST访问,看但的是Hello, admin!或者Bad username or password.

对于不了解GET与POST和HTML表单的同学,推荐去学习html基础。

但这样还是有些不灵活,用户访问看到的内容需要全部写出来,不能复用,太麻烦

使用模板引擎模板解决了我们上面的问题。先看一段代码

from flask import Flask, request, render_templateimport os

app= Flask(__name__)@app.route('/', methods=['GET','POST'])def home():

path='/'

all_file= os.listdir(path) return render_template('home.html',all_file= all_file)if __name__=='__main__':

app.run()这里读取了根目录下所有文件的名字,将其传给html模板页面

然后,在.py的同目录下建立目录templates,这里存放的是我们的模板,模板的特殊在于可以使用python指令及变量在html里

home.html

{% for i in all_file%}<a rel="external nofollow" href="/page/{{ i}}">{{ i}}</a>{% endfor%}{%%}中写的是指令

{{}}中写的是变量

所以最终的结果是,会生成多个标签,标签的名字就是目录名。

以上基础教程参照廖雪峰。

那么,基础已经将完了,接下来就会是成品了:

成品用我们上次爬取的图片来建站,good idea!

这里在.py脚本同目录下建立一个static目录存放图片。(图片放在.py所在目录外层会链接不到)

#beautiful_pic.pyfrom flask import Flaskfrom flask import requestfrom flask import render_templateimport os

app= Flask(__name__)#显示所有文件夹@app.route('/',methods=['GET','POST'])def list_all():

path='./static/mzitu/'

all_pic= os.listdir(path) return render_template('welcome.html',all_pic= all_pic)#具体展示图片@app.route('/<path>',methods=['GET','POST'])def list_pic(path):

#错误链接无法找到图片目录就提示错误链接

if(path not in os.listdir('./static/mzitu/')): return render_template('error.html')

pic_path='./static/mzitu/'+ path

all_pic= os.listdir(pic_path) return render_template('pic.html',title= path,all_pic= all_pic)if __name__=='__main__':#port为端口,host值为0.0.0.0即不单单只能在127.0.0.1访问,外网也能访问

app.run(host='0.0.0.0',port='2333')然后是模板文件

welcome.html

<!DOCTYPE html><html lang="en"><head>

<meta charset="UTF-8">

<title>欢迎来到福利页面</title></head><body>

{% for i in all_pic:%}<a rel="external nofollow" href="/{{i}}">{{i}}</a>

<br><br>

{% endfor%}</body></html>pic.html

<!DOCTYPE html><html lang="en"><head>

<meta charset="UTF-8">

<title>{{ title}}</title></head><body>

{% for i in all_pic%}<img src="./static/mzitu/{{title}}/{{i}}" alt="{{i}}">

<br>

{% endfor%}</body></html>error.html

<!DOCTYPE html><html lang="en"><head>

<meta charset="UTF-8">

<title>出错了</title></head><body>

你要访问的页面不存在...<br>

<a rel="external nofollow" href="/">点此返回首页</a></body></html>

好了,本文到此结束,如果可以帮助到大家,还望关注本站哦!

印尼服务器?东南亚外贸怎么选择服务器java游戏服务器框架 做java游戏服务端开发有前途吗