Python全栈 项目(HTTPServer、PiP使用)

简介: Python全栈、Python项目、练手项目、HTTPServer、HTTP协议、HTTP

pip是Python官方推荐的包管理工具    属于python的一部分


       pip的使用 

pip的安装
            sudo apt-get install python-pip
            sudo apt-get install python3-pip

安装包
            pip3  install   package

升级
            pip3  install  --upgrade  package

查看python包清单
            pip3 list

卸载
            pip3 uninstall  package

查找软件包
            pip3 search  package

显示软件包信息
            pip3 show  package

生成软件环境文件
            pip3  freeze  >  requirements.txt

根据环境文件安装第三方包
            pip3  install  -r  requirements.txt


from gevent import  monkey
           monkey.patch_all()
           功能 : 在socket导入之前使用后,用来修改套接字的阻塞行为

基于协程并发服务器模型:
        
import gevent 
# 在socket导入之前使用
from gevent import monkey 
monkey.patch_all()
from socket import * 
from time import ctime 


def server(port):
    s = socket()
    s.bind(('0.0.0.0',port))
    s.listen(5)
    while True:
        c,addr = s.accept()
        print("Connect from",addr)
        gevent.spawn(handler,c)

#处理客户端请求
def handler(c):
    while True:
        data = c.recv(1024).decode()
        if not data:
            break
        print("Receive:",data)
        c.send(ctime().encode())
    c.close()


if __name__ == "__main__":
    server(8888)



            HTTPServer

前端  前台  客户端  用户端
      功能 :
            1. 和用户进行交互,获取用户请求
            2. 和后端进行通信,整理用户请求给后端
            3. 接受后端数据内容,展现给用户

      要求:
            1. 良好的用户体验
            2. 较全面的交互能力
            3. 必要的前端优化
            4. 良好的跨平台型

后端  后台   服务端
      功能:
            1. 接受前端请求
            2. 进行逻辑处理和运算
            3. 和磁盘交互 (文件处理,数据库处理)
            4. 进行数据整理,更好的向前端返回结果

      要求:
            1. 更好的并发性
            2. 更快速的处理速度
            3. 更好的健壮性
            4. 可维护和可扩展
            5. 数据的安全

HTTPServer + Frame 版本

    httpserver 功能 : 
            1. 接受HTTP请求 (socket通信)
            2. 解析http请求 
               *  请求类型  GET,POST
               *  请求内容  
            3. 将具体的请求整理后给 web Frame
            4. 接受后端应用返回的数据内容
            5. 将数据组织为HTTP response的格式发给客户端



    什么是框架?
               矿建即开发模板,通过根据框架规则填写内容即可完成快速开发工作
   Frame 功能:
            1. 接收httpserver发送的request请求
            2. 进行逻辑处理或者数据整合
            3. 将结果发送给httpserver
                * 如果能够处理则返回结果和数据
                * 不能处理返回原因

      结构 :

HTTPServer --- static目录 
           --- HttpServer.py
   --- WebFrame.py
           --- setting.py
   --- views.py


m = __import__(module)
            功能 : 导入一个模块
            参数:要导入的模块
            返回值:模块对象

getattr(obj,attr)
            功能:获取一个对象的属性
            参数: obj   对象
                       attr  属性
            返回值: 返回属性值

__call__() 魔法方法
            作用 : 让实例对象可以像函数一样被调用执行

class CallTest(object):
    def __call__(self,a,b):
        print("This is call test")
        print("a =",a,"b =",b)

test = CallTest()
test(1,2)


HTTPServer完整代码:

Server:

#coding=utf-8

'''
module: HTTPServer.py
name : Paris
time : 2018-8-28
功能 :httpserver部分
modules: 
    Python3.5 、socket、sys
    threading、re、setting
'''
from socket import  *
import sys 
from threading import Thread
import re
from setting import * 

#处理http请求类
class HTTPServer(object):
    def __init__(self,application):
        self.sockfd = socket()
        self.sockfd.setsockopt\
        (SOL_SOCKET,SO_REUSEADDR,1)
        #获取模块接口
        self.application = application

    def bind(self,host,port):
        self.host = host
        self.port = port 
        self.sockfd.bind((self.host,self.port))
    #启动服务器
    def serve_forever(self):
        self.sockfd.listen(10)
        print("Listen the port %d..."%self.port)
        while True:
            connfd,addr = self.sockfd.accept()
            print("Connect from",addr)
            handle_client = Thread\
            (target = self.client_handler,\
                args = (connfd,))
            handle_client.setDaemon(True)
            handle_client.start()

    def client_handler(self,connfd):
        #接收浏览器request
        request = connfd.recv(4096)
        #可以分析请求头和请求体
        request_lines = request.splitlines()
        #获取请求行
        request_line = request_lines[0].decode('utf-8')
        
        #获取请求方法和请求内容
        pattern = r'(?P<METHOD>[A-Z]+)\s+(?P<PATH_INFO>/\S*)'
        try:
            env = re.match(pattern,request_line).groupdict()
        except:
            response_headlers =  "HTTP/1.1 500 SERVER ERROR\r\n"
            response_headlers += "\r\n"
            response_body = "server error"
            response = response_headlers + response_body
            connfd.send(response.encode())

        # method,filename = \
        # re.findall(r'^([A-Z]+)\s+(/\S*)', request_line)[0]

        #将解析内容合成字典给web frame使用
        # env = {'METHOD':method,'PATH_INFO':filename}
        # print(env)

        #将env给Frame处理,得到返回内容
        response = self.application(env)

        #发送给客户端
        if response:
            connfd.send(response.encode())
            connfd.close()


if __name__ == "__main__":
    #将要使用的模块导入进来
    sys.path.insert(1,MODULE_PATH)
    m = __import__(MODULE)
    application = getattr(m,APP)

    httpd = HTTPServer(application)
    httpd.bind(HOST,PORT)
    httpd.serve_forever()

setting:

# setting.py

#httpserver配置文件
HOST = '0.0.0.0'
PORT = 8000

#设置要使用的模块和应用
MODULE_PATH = "."  #设置Frame模块路径
MODULE = 'WebFrame'  #设置模块名称
APP = 'app'  #使用的应用


WebFrame:

#coding=utf-8 
from views import *
'''
WebFrame.py
WebFrame 框架
用于处理server解析请求
'''


#设置静态文件夹路径
STATIC_DIR = "./static"

#应用
class Application(object):
    def __init__(self,urls):
        self.urls = urls

    def __call__(self,env):
        method = env.get("METHOD",'GET')
        path = env.get("PATH_INFO",'/') #请求内容

        if method == 'GET':
            if path == '/' or path[-5:] == '.html':
                response = self.get_html(path)
            else:
                response = self.get_data(path)
        elif method == 'POST':
            pass

        return response

    def get_html(self,path):
        if path == '/':
            get_file = STATIC_DIR + "/index.html"
        else:
            get_file = STATIC_DIR + path
        try:
            fd = open(get_file)
        except IOError :
            #没有找到请求网页
            responseHeaders = "HTTP/1.1 404 not found\r\n"
            responseHeaders += '\r\n'
            response_body = "Sorry,the page not found"
        else:
            responseHeaders = "HTTP/1.1 200 OK\r\n"
            responseHeaders += '\r\n'
            response_body = fd.read()
        finally:
            response = responseHeaders + response_body
            return response

    def get_data(self,path):
        for url,handler in self.urls:
            if path == url:
                response_headers = "HTTP/1.1 200 OK\r\n"
                response_headers += '\r\n'
                response_body = handler()
                return response_headers + response_body 

        response_headers = "HTTP/1.1 404 not found\r\n"
        response_headers += '\r\n'
        response_body = "Sorry ,not found the data" 
        return response_headers + response_body

urls = [
    ('/time',show_time),
    ('/hello',say_hello),
    ('/bye',say_bye),
]

app = Application(urls)


views


# views.py
# 具体处理模块


import time

def show_time():
    return time.ctime()

def say_hello():
    return "hello world"

def say_bye():
    return "Good Bye"








python 的httpserver模块
            python2 BaseHTTPServer
            python3 http.server
示例:
     
try:
    from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
except ImportError:
    from http.server import BaseHTTPRequestHandler,HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print(self.headers) #请求头
        print(self.path)  #请求内容
        fd = open('test.html','rb')
        content = fd.read()
        #组织response
        self.send_response(200)
        self.send_header('Content-Type','text/html')
        self.end_headers()
        self.wfile.write(content)

    def do_POST(self): 
        pass


address = ('0.0.0.0',8080)
#生成httpserver对象
httpd = HTTPServer(address,RequestHandler)
httpd.serve_forever() #启动服务器

相关文章
|
1月前
|
机器学习/深度学习 人工智能 开发工具
人工智能项目的python版本管理工具DVC
dvc即data version control, 是一种针对人工智能项目(机器学习或者深度学习)的数据版本管理工具。DVC的操作和GIT类似,可以认为为GIT的二次开发封装。结合GIT,DVC可以有效的管理人工智能项目的整个流程,包括代码,数据,训练配置,模型【2月更文挑战第12天】
60 1
|
2月前
|
缓存 前端开发 测试技术
(译)Python 官方团队在打包项目中踩过的坑
(译)Python 官方团队在打包项目中踩过的坑
31 2
|
2月前
|
数据采集 存储 架构师
上进计划 | Python爬虫经典实战项目——电商数据爬取!
在如今这个网购风云从不间歇的时代,购物狂欢持续不断,一年一度的“6.18年中大促”、“11.11购物节”等等成为了网购电商平台的盛宴。在买买买的同时,“如何省钱?”成为了大家最关心的问题。 比价、返利、优惠券都是消费者在网购时的刚需,但在这些“优惠”背后已产生灰色地带。
|
14天前
|
JavaScript 前端开发 Docker
全栈开发实战:结合Python、Vue和Docker进行部署
【4月更文挑战第10天】本文介绍了如何使用Python、Vue.js和Docker进行全栈开发和部署。Python搭配Flask创建后端API,Vue.js构建前端界面,Docker负责应用的容器化部署。通过编写Dockerfile,将Python应用构建成Docker镜像并运行,前端部分使用Vue CLI创建项目并与后端交互。最后,通过Nginx和另一个Dockerfile部署前端应用。这种组合提升了开发效率,保证了应用的可维护性和扩展性,适合不同规模的企业使用。
|
24天前
|
前端开发 JavaScript 数据管理
描述一个使用Python开发Web应用程序的实际项目经验,包括所使用的框架和技术栈。
使用Flask开发Web应用,结合SQLite、Flask-SQLAlchemy进行数据管理,HTML/CSS/JS(Bootstrap和jQuery)构建前端。通过Flask路由处理用户请求,模块化代码提高可维护性。unittest进行测试,开发阶段用内置服务器,生产环境可选WSGI服务器或容器化部署。实现了用户注册登录和数据管理功能,展示Python Web开发的灵活性和效率。
14 4
|
1月前
|
Python
老男孩&路飞学城Python全栈
老男孩&路飞学城的Python全栈开发重点班由ALEX老师主讲,核心教学内容,100多天课程,近100G资料,含基础到实战。一线技术专家亲授,以案例教学引导学生逐步进入项目实战。
20 1
老男孩&路飞学城Python全栈
|
1月前
|
Linux 数据库连接 数据库
Python如何将项目直接打包为一键整合包
Python如何将项目直接打包为一键整合包
41 0
|
1月前
|
数据采集 存储 数据处理
Python爬虫在Django项目中的数据处理与展示实例
Python爬虫在Django项目中的数据处理与展示实例
|
1月前
|
人工智能 开发工具 git
第一次运行 Python 项目,使用 python-pptx 提取 ppt 中的文字和图片
人工智能时代,最需要学习的编程语言是:python 。笔者是个 python 小白,昨天花了两个小时,第一次成功运行起来 python 项目 。 项目是 powerpoint-extractor ,可以将 ppt 文件中的图片提取出来,并输出到固定的目录。
第一次运行 Python 项目,使用 python-pptx 提取 ppt 中的文字和图片
|
2月前
|
Web App开发 人工智能 Kubernetes
Python 潮流周刊#23:35 个容易上手的 Python 小项目
Python 潮流周刊#23:35 个容易上手的 Python 小项目
20 1