python 雜記

進程html

fork()函數
Unix/Linux操做系統提供了一個fork()系統調用,它很是特殊。普通的函數調用,調用一次,返回一次,可是fork()調用一次,返回兩次,由於操做系統自動把當前進程(稱爲父進程)複製了一份(稱爲子進程),而後,分別在父進程和子進程內返回。

子進程永遠返回0,而父進程返回子進程的ID。這樣作的理由是,一個父進程能夠fork出不少子進程,因此,父進程要記下每一個子進程的ID,而子進程只須要調用getppid()就能夠拿到父進程的ID。python

Python的os模塊封裝了常見的系統調用,其中就包括fork,能夠在Python程序中輕鬆建立子進程:mysql

import os
print('process %s is start' % os.getpid())
pid = os.fork()
print(pid)
if pid==0:
print('fatherID: %s childID :%s' % (os.getppid(),os.getpid()))
else:
print('fatherID: %s childID :%s' % (os.getpid(),pid))web

結果:
這裏寫圖片描述
name == ‘main’正則表達式

if name==’main‘: 是將本模塊中的代碼進行隔絕,使得該模塊被調用時不想被執行的代碼不會執行。知足條件意味着是運行的本模塊而不是被調用。參考這裏寫連接內容

線程鎖sql

import time,threading
blance =0
def thread_change(n):
global blance
blance =blance+1
blance =blance-1數據庫

lock = threading.Lock()
def thread_run(n):
for i in range(1000000):
# thread_change(n) #若是不使用線程鎖就會出現錯誤
lock.acquire()
try:
thread_change(n)
finally:
lock.release()django

建立兩個線程運行thread_run

f1 = threading.Thread(target=thread_run,args=(5,))
f2 = threading.Thread(target=thread_run,args=(8,))
f1.start()
f2.start()
f1.join()
f2.join()
print(blance)flask

正則表達式windows

字符匹配

匹配類型的

. #任意字符類型除了換行符,配合re.S使用
\d #匹配數字
\w #數字或者字母
\s #匹配空格

匹配數量的

  • #匹配任意數量的字符
  • #匹配至少一個字符
    ? #0或1個字符
    {n} #匹配n個字符
    {n-m} #匹配n-m個字符

eg:

code = 'xyx123'
b = re.findall('x*',code) # ['x', '', 'x', '', '', '', '']

與?區別
code = 'xxixxlovexxyouxx'
b =re.findall('xx.
xx',code)

print(b) #['xxixxlovexxyouxx']
code = 'xxixxlovexxyouxx'
b =re.findall('xx.?xx',code)
print(b) #['xxixx']

非貪心獲取

code = 'xxixx232xxlovexx324xxyouxx'
b =re.findall('xx(.*?)xx',code)
print(b) #['i', 'love', 'you']

判斷字符串是不是qq郵箱

import re
qq = input()#2.7控制檯輸入要加''不然會出錯。
if re.match(r'.+@qq.com',qq):
print('是qq郵箱')
else:
print('不是qq郵箱')

字符串切割

'a,b;; c d'字符串分割

import re
print(re.split(r'[\s,;]+','a,b;; c d'))#+的做用是至少匹配list中的一項。

結果['a', 'b', 'c', 'd']

分組

import re
qq = input()
if re.match(r'^(.+)(@)(qq)(.com)\(',qq): print('是qq郵箱') else: print('不是qq郵箱') print(re.match(r'^(.+)(@)(qq)(\.com)\)',qq).groups())
import re
qq = input()

運行結果

eric@qq.com
是qq郵箱
('eric', '@', 'qq', '.com')

sqlite3

import sqlite3

連接表

conn = sqlite3.connect('test.db')

新建光標

cursor = conn.cursor()

經過光標執行建立user表

cursor.execute('create table user (id varchar(20) primary key ,name varchar(20)) ')

執行插入一條數據

cursor.execute('insert into user (id,name) values ( '1','eric') ')

經過光標獲取數據條數

print(cursor.rowcount)

關閉光標

cursor.close()

提交事務

conn.commit()

關閉連接

conn.close()

import sqlite3
conn =sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('select * from user where id = ?',('1',))
values = cursor.fetchall()
print(values)
cursor.close()

conn.commit() 只有在改變數據庫的動做下才須要提交事務

conn.close()

mysql 示例

先建立test數據庫

mysqladmin -u root -p create RUNOOB

import mysql.connector
conn = mysql.connector.connect(user = 'root',password ='admin',database ='test')
cursor = conn.cursor()
cursor.execute('create table user (id varchar(20) primary key,name varchar(20))')
cursor.execute('insert into user (id ,name) values (%s,%s)' , ['1', 'eric'])
print(cursor.rowcount)
cursor.close()
conn.commit()

執行查詢

cursor =conn.cursor()
cursor.execute('select * from user where id =%s' ,('1',))
values = cursor.fetchall()
print(values)

SQLAlchemy

SQLAlchemy用一個字符串表示鏈接信息:

'數據庫類型+數據庫驅動名稱://用戶名:口令@機器地址:端口號/數據庫名'

import sqlalchemy
from sqlalchemy import Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base

建立ORM 框架對象基類

from sqlalchemy.orm import sessionmaker

Base =declarative_base()

定義基於基類的對象

class User(Base):
#表名字
tablename='user'
#對應表結構
id = Column(String(20),primary_key=True)
name = Column(String(20))

初始化數據鏈接

engine = create_engine('mysql+mysqlconnector://root:admin@localhost:3306/test')

建立DBSession類,經過兩個類建立的DBSession類就能夠實現對象化的數據庫操做

DBSession = sessionmaker(bind=engine)

測試:建立對象進行存儲

建立DBSession對象

session = DBSession()

建立要存儲的user對象

user1 = User(id ='12',name ='eric')# type:main.User
session.add(user1)
session.commit()
session.close()

經過DBSession類對象進行數據的查詢

session = DBSession()
user2 = session.query(User).filter(User.id=='12').one()
print(type(user2))
print(user2)

HTTP格式

每一個HTTP請求和響應都遵循相同的格式,一個HTTP包含Header和Body兩部分,其中Body是可選的。

HTTP協議是一種文本協議,因此,它的格式也很是簡單。HTTP GET請求的格式:

GET /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3
每一個Header一行一個,換行符是\r\n。

HTTP POST請求的格式:

POST /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...
當遇到連續兩個\r\n時,Header部分結束,後面的數據所有是Body。

HTTP響應的格式:

200 OK
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...
HTTP響應若是包含body,也是經過\r\n\r\n來分隔的。請再次注意,Body的數據類型由Content-Type頭來肯定,若是是網頁,Body就是文本,若是是圖片,Body就是圖片的二進制數據。

當存在Content-Encoding時,Body數據是被壓縮的,最多見的壓縮方式是gzip,因此,看到Content-Encoding: gzip時,須要將Body數據先解壓縮,才能獲得真正的數據。壓縮的目的在於減小Body的大小,加快網絡傳輸。

WSGI 接口使用
hello.py

def application(environ,start_response):
start_response('200 OK',[('Content-Type','text/html')])
return [b'

hello, web!

']

server.py

建立一個服務器ip爲空,端口8000,處理函數application

from wsgiref.simple_server import make_server

from hello import application

httpd = make_server('',8001,application)
print('serving http on port 8001')

開始監聽http請求

httpd.serve_forever()

Flask框架使用

from flask import Flask
from flask import request

app = Flask(name)

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

Home

'

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





'''

@app.route('/signin', methods=['POST'])
def signin():
# 須要從request對象讀取表單內容:
if request.form['username']=='admin' and request.form['password']=='password':
return '

Hello, admin!

'
return '

Bad username or password.

'

if name == 'main':
app.run()

yield next() send()

def h():
print ('wenchuan')
m = yield 5 # Fighting!
print (m)
d = yield 12
print ('We are together!')
c = h()
x = next(c) #x 獲取了yield 5 的參數值 5
y = c.send('Fighting!') #y 獲取了yield 12 的參數值12
print ('We will never forget the date', x, '.', y)

next() 使得阻塞打開,運行到當前yield處

send() 使運行到當前yield並給上個yield傳值

m=yield 5 m會得到send()傳過來的值

x=next() x會得到yield的參數5

yield from

至關於

for item in iterater:
yield item

生成器將任務分給子迭代器
aiohttp

實現多線程的網絡io併發

aiohttp 編寫一個web服務器 /返回 index /hello/name 放回 hello name

import asyncio

from copy import name

from aiohttp import web

async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'

Index

',content_type='text/html')
async def hello(request):
await asyncio.sleep(0.5)
text = '

hello,%s

' % request.match_info['name']
return web.Response(body=text.encode('utf-8'),content_type='text/html')

aiohttp的初始化函數

async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET','/',index)
app.router.add_route('GET','/hello/{name}',hello)
srv = await loop.create_server(app.make_handler(),'127.0.0.1',8003)
print('server start at http://127.0.0.1:8000')
return srv
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

flask

基於OAuth的受權碼模式
項目練習地址
OAuth

阮一峯OAuth
名詞解釋:

(1) Third-party application:第三方應用程序,本文中又稱"客戶端"(client),即上一節例子中的"雲沖印"。

(2)HTTP service:HTTP服務提供商,本文中簡稱"服務提供商",即上一節例子中的Google。

(3)Resource Owner:資源全部者,本文中又稱"用戶"(user)。

(4)User Agent:用戶代理,本文中就是指瀏覽器。

(5)Authorization server:認證服務器,即服務提供商專門用來處理認證的服務器。

(6)Resource server:資源服務器,即服務提供商存放用戶生成的資源的服務器。它與認證服務器,能夠是同一臺服務器,也能夠是不一樣的服務器。

OAuth工做流程
這裏寫圖片描述



(A)用戶打開客戶端之後,客戶端要求用戶給予受權。

(B)用戶贊成給予客戶端受權。

(C)客戶端使用上一步得到的受權,向認證服務器申請令牌。

(D)認證服務器對客戶端進行認證之後,確認無誤,贊成發放令牌。

(E)客戶端使用令牌,向資源服務器申請獲取資源。

(F)資源服務器確認令牌無誤,贊成向客戶端開放資源。

爬蟲爬取特定內容

項目地址

import re

import requests as requests

source = open('source.txt', 'r')
html = source.read()
linkList = re.findall('img src="(.*?)" class="lessonimg"', html, re.S)
i = 1
for link in linkList:
print('downloding the %s picture' % i)
downing = requests.get(link)
fp = open('pic//' + str(i) + '.jpg', 'wb')
fp.write(downing.content)
fp.close()
i += 1

從百度爬取二哈
目前只能單頁爬取

import re

import requests
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0'}
html = requests.post('http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E5%93%88%E5%A3%AB%E5%A5%87/pageName=2',headers=headers)
print(html.headers)
file = open('test.txt','wb')
file.write(html.content)

獲取圖片地址

picUrl = re.findall('"objURL":"(.*?)"',html.text,re.S)
i = 0
for each in picUrl:
i += 1
if not (i ==16 or i==22 or i==24):
picFile = open('dogPic//'+str(i)+'.jpg','wb')
picContent = requests.get(each)
#經獲取的圖片數據寫入文件
picFile.write(picContent.content)
print('第%d張圖片爬取完成'%(i))
else:
pass

split(char,num)

char 爲空默認 空格 換行 或 \t
num 表示分割幾回
pip 安裝

sudo easy_install pip

virtualenv 虛擬環境

廖雪峯virtualenv

  • 安裝

pip3 virtualevn

安裝在當前帳戶目錄下
/Users/eric/.virtualenvs/
這裏寫圖片描述
建立一個純淨的獨立python3環境

virtualenv --no-site-packages venv

啓用虛擬環境

source venv/bin/activate

退出虛擬環境

deactivate

virtualenvwrapper安裝

安裝及初始化

安裝

pip install virtualenvwrapper

初始化

export WORKON_HOME='~/.virtualenvs'
source /usr/local/bin/virtualenvwrapper.sh
source ~/.bashrc

建立2.7版本的虛擬環境

mkvirtualenv -p python2.7 env2.7

建立一個Python2.7純淨版的虛擬環境

mkvirtualenv -p python2.7 --no-site-packages py2.7django1.8

退出當前環境

deactivate

進入、列出、刪除

workon env
lsvirtualenv
rmvirtualenv

找到python安裝路徑

Mac

type -a python3

sublime python配置

這裏寫連接內容
windows 控制檯切換python版本

默認控制檯啓動的版本是第一個添加環境變量的版本,須要那個就像暫時改動環境變量吧。
property

屬性參考

簡介:
經過裝飾器將類方法封裝成屬性。

class Student(object):

def get_score(self):
    return self._score

def set_score(self, value):
    if not isinstance(value, int):
        raise ValueError('score must be an integer!')
    if value < 0 or value > 100:
        raise ValueError('score must between 0 ~ 100!')
    self._score = value
相關文章
相關標籤/搜索