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() #启动服务器

Python全栈 项目(HTTPServer、PiP使用)的更多相关文章

  1. Python全栈 项目(电子词典、协程、pdb调试)

    后面我就不截图了 大家还是看原文吧                          https://yq.aliyun.com/articles/629534 . ................. ...

  2. 老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】

    点击了解更多Python课程>>> 老男孩Python全栈第2期+课件笔记[高清完整92天整套视频教程] 课程目录 ├─day01-python 全栈开发-基础篇 │ 01 pyth ...

  3. Python全栈开发【面向对象进阶】

    Python全栈开发[面向对象进阶] 本节内容: isinstance(obj,cls)和issubclass(sub,super) 反射 __setattr__,__delattr__,__geta ...

  4. Python全栈开发【面向对象】

    Python全栈开发[面向对象] 本节内容: 三大编程范式 面向对象设计与面向对象编程 类和对象 静态属性.类方法.静态方法 类组合 继承 多态 封装 三大编程范式 三大编程范式: 1.面向过程编程 ...

  5. 战争热诚的python全栈开发之路

    从学习python开始,一直是自己摸索,但是时间不等人啊,所以自己为了节省时间,决定报个班系统学习,下面整理的文章都是自己学习后,认为重要的需要弄懂的知识点,做出链接,一方面是为了自己找的话方便,一方 ...

  6. Win10构建Python全栈开发环境With WSL

    目录 Win10构建Python全栈开发环境With WSL 启动WSL 总结 对<Dev on Windows with WSL>的补充 Win10构建Python全栈开发环境With ...

  7. python 全栈开发,Day117(popup,Model类的继承,crm业务开发)

    昨日内容回顾 第一部分:权限相关 1. 权限基本流程 用户登录成功后获取权限信息,将[权限和菜单]信息写入到session. 以后用户在来访问,在中间件中进行权限校验. 为了提升用户体验友好度,在后台 ...

  8. python 全栈开发,Day99(作业讲解,DRF版本,DRF分页,DRF序列化进阶)

    昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...

  9. python 全栈开发,Day98(路飞学城背景,django ContentType组件,表结构讲解)

    昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...

随机推荐

  1. 设计模式——Spirng_Bean工厂

    前言:对于简单工厂和抽象工厂都有自己的优点和缺点, 比如简单工厂,如果你需要实现的类过多,你最后会出现工厂泛滥的情况,没有有效的控制代码的可重复性.http://www.cnblogs.com/xia ...

  2. win7利用winSCP上传文件到ubuntu server

    1.为ubuntu server设置root密码: sudo passwd root 先设密码在登录 2. su root进入root账户: 3.安装SSH:sudo apt-get install ...

  3. 【Javascript-ECMA6-Fetch详解】

    Fetch 由于Fetch API是基于Promise设计,因此旧的浏览器并不支持该API,需要引用时引用es6-promise. 基本知识 fetch请求返回response格式 body Fetc ...

  4. position定位笔记

    position定位 position一共有四个可选属性:static/relative/absolute/fixed 代码: <style type="text/css"& ...

  5. springBoot 官方整合的redis 使用教程:(StringRedisTemplate 方式存储 Object类型value)

    前言:最近新项目准备用 redis 简单的缓存 一些查询信息,以便第二次查询效率高一点. 项目框架:springBoot.java.maven  说明:edis存储的数据类型,key一般都是Strin ...

  6. CSS、JavaScript学习过程

    初学JavaScript,通过博客记录自己学习过程中遇到的问题.(包含少量CSS) 零碎记录 JavaScript 输出 type="text/javascript" 那些老旧的实 ...

  7. netstat命令的用法

    netstat用于显示与IP.TCP.UDP和ICMP协议相关的统计数据,一般用于检验本机各端口的网络连接情况.利用netstat指令可让你得知整个Linux系统的网络情况.参数:-a或–all 显示 ...

  8. chromium之scoped_ptr

    看看怎么使用 // Scopers help you manage ownership of a pointer, helping you easily manage the // a pointer ...

  9. ubuntu18.04错误配置变量环境导致无法进入系统

    1.问题描述 错误配置环境变量(直接在/etc/profile文件末尾添加了export xxx),关机后一直在登录界面循环无法进入系统. ###环境变量的添加是在原有变量之后以冒号(:)分隔加入,并 ...

  10. Oracle条件判断列数量非where

    sum(case when typename='测试' then 1 else 0 end)