日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python實(shí)用代碼片段收集貼

系統(tǒng) 1832 0

獲取一個(gè)類的所有子類

復(fù)制代碼 代碼如下:

def itersubclasses(cls, _seen=None):
??? """Generator over all subclasses of a given class in depth first order."""
??? if not isinstance(cls, type):
??????? raise TypeError(_('itersubclasses must be called with '
????????????????????????? 'new-style classes, not %.100r') % cls)
??? _seen = _seen or set()
??? try:
??????? subs = cls.__subclasses__()
??? except TypeError:?? # fails only when cls is type
??????? subs = cls.__subclasses__(cls)
??? for sub in subs:
??????? if sub not in _seen:
??????????? _seen.add(sub)
??????????? yield sub
??????????? for sub in itersubclasses(sub, _seen):
??????????????? yield sub

簡(jiǎn)單的線程配合

復(fù)制代碼 代碼如下:

import threading
is_done = threading.Event()
consumer = threading.Thread(
??? target=self.consume_results,
??? args=(key, self.task, runner.result_queue, is_done))
consumer.start()
self.duration = runner.run(
??????? name, kw.get("context", {}), kw.get("args", {}))
is_done.set()
consumer.join() #主線程堵塞,直到consumer運(yùn)行結(jié)束

多說一點(diǎn),threading.Event()也可以被替換為threading.Condition(),condition有notify(), wait(), notifyAll()。解釋如下:
復(fù)制代碼 代碼如下:

The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in another thread. Once awakened, it re-acquires the lock and returns. It is also possible to specify a timeout.
The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. The notifyAll() method wakes up all threads waiting for the condition variable.
Note: the notify() and notifyAll() methods don't release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.

復(fù)制代碼 代碼如下:

# Consume one item
cv.acquire()
while not an_item_is_available():
??? cv.wait()
get_an_available_item()
cv.release()
# Produce one item
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()

計(jì)算運(yùn)行時(shí)間

復(fù)制代碼 代碼如下:

class Timer(object):
??? def __enter__(self):
??????? self.error = None
??????? self.start = time.time()
??????? return self
??? def __exit__(self, type, value, tb):
??????? self.finish = time.time()
??????? if type:
??????????? self.error = (type, value, tb)
??? def duration(self):
??????? return self.finish - self.start
with Timer() as timer:
??? func()
return timer.duration()

元類

__new__()方法接收到的參數(shù)依次是:
當(dāng)前準(zhǔn)備創(chuàng)建的類的對(duì)象;
類的名字;
類繼承的父類集合;
類的方法集合;

復(fù)制代碼 代碼如下:

class ModelMetaclass(type):
??? def __new__(cls, name, bases, attrs):
??????? if name=='Model':
??????????? return type.__new__(cls, name, bases, attrs)
??????? mappings = dict()
??????? for k, v in attrs.iteritems():
??????????? if isinstance(v, Field):
??????????????? print('Found mapping: %s==>%s' % (k, v))
??????????????? mappings[k] = v
??????? for k in mappings.iterkeys():
??????????? attrs.pop(k)
??????? attrs['__table__'] = name # 假設(shè)表名和類名一致
??????? attrs['__mappings__'] = mappings # 保存屬性和列的映射關(guān)系
??????? return type.__new__(cls, name, bases, attrs)
class Model(dict):
??? __metaclass__ = ModelMetaclass
??? def __init__(self, **kw):
??????? super(Model, self).__init__(**kw)
??? def __getattr__(self, key):
??????? try:
??????????? return self[key]
??????? except KeyError:
??????????? raise AttributeError(r"'Model' object has no attribute '%s'" % key)
??? def __setattr__(self, key, value):
??????? self[key] = value
??? def save(self):
??????? fields = []
??????? params = []
??????? args = []
??????? for k, v in self.__mappings__.iteritems():
??????????? fields.append(v.name)
??????????? params.append('?')
??????????? args.append(getattr(self, k, None))
??????? sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
??????? print('SQL: %s' % sql)
??????? print('ARGS: %s' % str(args))
class Field(object):
??? def __init__(self, name, column_type):
??????? self.name = name
??????? self.column_type = column_type
??? def __str__(self):
??????? return '<%s:%s>' % (self.__class__.__name__, self.name)
class StringField(Field):
??? def __init__(self, name):
??????? super(StringField, self).__init__(name, 'varchar(100)')
class IntegerField(Field):
??? def __init__(self, name):
??????? super(IntegerField, self).__init__(name, 'bigint')
class User(Model):
??? # 定義類的屬性到列的映射:
??? id = IntegerField('id')
??? name = StringField('username')
??? email = StringField('email')
??? password = StringField('password')
# 創(chuàng)建一個(gè)實(shí)例:
u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
# 保存到數(shù)據(jù)庫:
u.save()

輸出如下:

復(fù)制代碼 代碼如下:

Found model: User
Found mapping: email ==>
Found mapping: password ==>
Found mapping: id ==>
Found mapping: name ==>
SQL: insert into User (password,email,username,uid) values (?,?,?,?)
ARGS: ['my-pwd', 'test@orm.org', 'Michael', 12345]

SQLAlchemy簡(jiǎn)單使用

復(fù)制代碼 代碼如下:

# 導(dǎo)入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 創(chuàng)建對(duì)象的基類:
Base = declarative_base()
# 定義User對(duì)象:
class User(Base):
??? # 表的名字:
??? __tablename__ = 'user'
??? # 表的結(jié)構(gòu):
??? id = Column(String(20), primary_key=True)
??? name = Column(String(20))
# 初始化數(shù)據(jù)庫連接:
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test') # '數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動(dòng)名稱://用戶名:口令@機(jī)器地址:端口號(hào)/數(shù)據(jù)庫名'
# 創(chuàng)建DBSession類型:
DBSession = sessionmaker(bind=engine)
# 創(chuàng)建新User對(duì)象:
new_user = User(id='5', name='Bob')
# 添加到session:
session.add(new_user)
# 提交即保存到數(shù)據(jù)庫:
session.commit()
# 創(chuàng)建Query查詢,filter是where條件,最后調(diào)用one()返回唯一行,如果調(diào)用all()則返回所有行:
user = session.query(User).filter(User.id=='5').one()
# 關(guān)閉session:
session.close()

WSGI簡(jiǎn)單使用和Web框架Flask的簡(jiǎn)單使用

復(fù)制代碼 代碼如下:

from wsgiref.simple_server import make_server
def application(environ, start_response):
??? start_response('200 OK', [('Content-Type', 'text/html')])
??? return '

Hello, web!

'
# 創(chuàng)建一個(gè)服務(wù)器,IP地址為空,端口是8000,處理函數(shù)是application:
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
# 開始監(jiān)聽HTTP請(qǐng)求:
httpd.serve_forever()

了解了WSGI框架,我們發(fā)現(xiàn):其實(shí)一個(gè)Web App,就是寫一個(gè)WSGI的處理函數(shù),針對(duì)每個(gè)HTTP請(qǐng)求進(jìn)行響應(yīng)。
但是如何處理HTTP請(qǐng)求不是問題,問題是如何處理100個(gè)不同的URL。
一個(gè)最簡(jiǎn)單和最土的想法是從environ變量里取出HTTP請(qǐng)求的信息,然后逐個(gè)判斷。

復(fù)制代碼 代碼如下:

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對(duì)象讀取表單內(nèi)容:
??? if request.form['username']=='admin' and request.form['password']=='password':
??????? return '

Hello, admin!

'
??? return '

Bad username or password.

'
if __name__ == '__main__':
??? app.run()

格式化顯示json

復(fù)制代碼 代碼如下:

print(json.dumps(data, indent=4))
# 或者
import pprint
pprint.pprint(data)

實(shí)現(xiàn)類似Java或C中的枚舉

復(fù)制代碼 代碼如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
import sys
class ImmutableMixin(object):
??? _inited = False
??? def __init__(self):
??????? self._inited = True
??? def __setattr__(self, key, value):
??????? if self._inited:
??????????? raise Exception("unsupported action")
??????? super(ImmutableMixin, self).__setattr__(key, value)
class EnumMixin(object):
??? def __iter__(self):
??????? for k, v in itertools.imap(lambda x: (x, getattr(self, x)), dir(self)):
??????????? if not k.startswith('_'):
??????????????? yield v
class _RunnerType(ImmutableMixin, EnumMixin):
??? SERIAL = "serial"
??? CONSTANT = "constant"
??? CONSTANT_FOR_DURATION = "constant_for_duration"
??? RPS = "rps"
if __name__=="__main__":
??? print _RunnerType.CONSTANT

創(chuàng)建文件時(shí)指定權(quán)限

復(fù)制代碼 代碼如下:

import os
def write_to_file(path, contents, umask=None):
??? """Write the given contents to a file
??? :param path: Destination file
??? :param contents: Desired contents of the file
??? :param umask: Umask to set when creating this file (will be reset)
??? """
??? if umask:
??????? saved_umask = os.umask(umask)
??? try:
??????? with open(path, 'w') as f:
??????????? f.write(contents)
??? finally:
??????? if umask:
??????????? os.umask(saved_umask)
if __name__ == '__main__':
??? write_to_file('/home/kong/tmp', 'test', 31)
??? # Then you will see a file is created with permission 640.
??? # Warning: If the file already exists, its permission will not be changed.
??? # Note:For file, default all permission is 666, and 777 for directory.

多進(jìn)程并發(fā)執(zhí)行

復(fù)制代碼 代碼如下:

import multiprocessing
import time
import os
def run(flag):
??? print "flag: %s, sleep 2s in run" % flag
??? time.sleep(2)
??? print "%s exist" % flag
??? return flag
if __name__ == '__main__':
??? pool = multiprocessing.Pool(3)
??? iter_result = pool.imap(run, xrange(6))
??? print "sleep 5s\n\n"
??? time.sleep(5)
??? for i in range(6):
??????? try:
??????????? result = iter_result.next(600)
??????? except multiprocessing.TimeoutError as e:
??????????? raise
??????? print result
??? pool.close()
??? pool.join()

運(yùn)行時(shí)自動(dòng)填充函數(shù)參數(shù)

復(fù)制代碼 代碼如下:

import decorator
def default_from_global(arg_name, env_name):
??? def default_from_global(f, *args, **kwargs):
??????? id_arg_index = f.func_code.co_varnames.index(arg_name)
??????? args = list(args)
??????? if args[id_arg_index] is None:
??????????? args[id_arg_index] = get_global(env_name)
??????????? if not args[id_arg_index]:
??????????????? print("Missing argument: --%(arg_name)s" % {"arg_name": arg_name})
??????????????? return(1)
??????? return f(*args, **kwargs)
??? return decorator.decorator(default_from_global)
# 如下是一個(gè)裝飾器,可以用在需要自動(dòng)填充參數(shù)的函數(shù)上。功能是:
# 如果沒有傳遞函數(shù)的deploy_id參數(shù),那么就從環(huán)境變量中獲取(調(diào)用自定義的get_global函數(shù))
with_default_deploy_id = default_from_global('deploy_id', ENV_DEPLOYMENT)???

嵌套裝飾器

validator函數(shù)裝飾func1,func1使用時(shí)接收參數(shù)(*arg, **kwargs),而func1又裝飾func2(其實(shí)就是Rally中的scenario函數(shù)),給func2增加validators屬性,是一個(gè)函數(shù)的列表,函數(shù)的接收參數(shù)config, clients, task。這些函數(shù)最終調(diào)用func1,傳入?yún)?shù)(config, clients, task, *args, **kwargs),所以func1定義時(shí)參數(shù)是(config, clients, task, *arg, **kwargs)?
最終實(shí)現(xiàn)的效果是,func2有很多裝飾器,每個(gè)都會(huì)接收自己的參數(shù),做一些校驗(yàn)工作。

復(fù)制代碼 代碼如下:

def validator(fn):
??? """Decorator that constructs a scenario validator from given function.
??? Decorated function should return ValidationResult on error.
??? :param fn: function that performs validation
??? :returns: rally scenario validator
??? """
??? def wrap_given(*args, **kwargs):
??????? """Dynamic validation decorator for scenario.
??????? :param args: the arguments of the decorator of the benchmark scenario
??????? ex. @my_decorator("arg1"), then args = ('arg1',)
??????? :param kwargs: the keyword arguments of the decorator of the scenario
??????? ex. @my_decorator(kwarg1="kwarg1"), then kwargs = {"kwarg1": "kwarg1"}
??????? """
??????? def wrap_validator(config, clients, task):
??????????? return (fn(config, clients, task, *args, **kwargs) or
??????????????????? ValidationResult())
??????? def wrap_scenario(scenario):
??????????? wrap_validator.permission = getattr(fn, "permission",
??????????????????????????????????????????????? consts.EndpointPermission.USER)
??????????? if not hasattr(scenario, "validators"):
??????????????? scenario.validators = []
??????????? scenario.validators.append(wrap_validator)
??????????? return scenario
??????? return wrap_scenario
??? return wrap_given

inspect庫的一些常見用法

inspect.getargspec(func) 獲取函數(shù)參數(shù)的名稱和默認(rèn)值,返回一個(gè)四元組(args, varargs, keywords, defaults),其中:
args是參數(shù)名稱的列表;
varargs和keywords是*號(hào)和**號(hào)的變量名稱;
defaults是參數(shù)默認(rèn)值的列表;

inspect.getcallargs(func[, *args][, **kwds]) 綁定函數(shù)參數(shù)。返回綁定后函數(shù)的入?yún)⒆值洹?

python中的私有屬性和函數(shù)

Python把以兩個(gè)或以上下劃線字符開頭且沒有以兩個(gè)或以上下劃線結(jié)尾的變量當(dāng)作私有變量。私有變量會(huì)在代碼生成之前被轉(zhuǎn)換為長(zhǎng)格式(變?yōu)楣校@個(gè)過程叫"Private name mangling",如類A里的__private標(biāo)識(shí)符將被轉(zhuǎn)換為_A__private,但當(dāng)類名全部以下劃線命名的時(shí)候,Python就不再執(zhí)行軋壓。而且,雖然叫私有變量,仍然有可能被訪問或修改(使用_classname__membername),所以, 總結(jié)如下:

無論是單下劃線還是雙下劃線開頭的成員,都是希望外部程序開發(fā)者不要直接使用這些成員變量和這些成員函數(shù),只是雙下劃線從語法上能夠更直接的避免錯(cuò)誤的使用,但是如果按照_類名__成員名則依然可以訪問到。單下劃線的在動(dòng)態(tài)調(diào)試時(shí)可能會(huì)方便一些,只要項(xiàng)目組的人都遵守下劃線開頭的成員不直接使用,那使用單下劃線或許會(huì)更好。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 崇礼县| 郎溪县| 乐至县| 漳浦县| 扎囊县| 涡阳县| 新乡县| 陵川县| 嘉义市| 台南市| 凤冈县| 汉川市| 浠水县| 大理市| 桂东县| 朝阳区| 綦江县| 松桃| 拉孜县| 哈巴河县| 沁阳市| 双柏县| 德惠市| 莱西市| 加查县| 唐山市| 长乐市| 阿拉善右旗| 墨江| 出国| 敖汉旗| 大庆市| 中江县| 扬州市| 平湖市| 吉隆县| 宿松县| 喀喇| 班戈县| 固安县| 迭部县|