欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2015年06月03日 09:22:09   投稿:junjie  
這篇文章主要介紹了python實(shí)用代碼片段收集貼,本文收集了如獲取一個(gè)類的所有子類、計(jì)算運(yùn)行時(shí)間、SQLAlchemy簡(jiǎn)單使用、實(shí)現(xiàn)類似Java或C中的枚舉等實(shí)用功能代碼,需要的朋友可以參考下

獲取一個(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é)束

多說(shuō)一點(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ù)庫(kù):
u.save()

輸出如下:

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

Found model: User
Found mapping: email ==> <StringField:email>
Found mapping: password ==> <StringField:password>
Found mapping: id ==> <IntegerField:uid>
Found mapping: name ==> <StringField:username>
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ù)庫(kù)連接:
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test') # '數(shù)據(jù)庫(kù)類型+數(shù)據(jù)庫(kù)驅(qū)動(dòng)名稱://用戶名:口令@機(jī)器地址:端口號(hào)/數(shù)據(jù)庫(kù)名'
# 創(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ù)庫(kù):
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 '<h1>Hello, web!</h1>'
# 創(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)求不是問(wèn)題,問(wèn)題是如何處理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 '<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對(duì)象讀取表單內(nèi)容:
    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()

格式化顯示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ù)上。功能是:
# 如果沒(méi)有傳遞函數(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庫(kù)的一些常見用法

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)⒆值洹?/p>

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

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

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

相關(guān)文章

  • 基于Python新建用戶并產(chǎn)生隨機(jī)密碼過(guò)程解析

    基于Python新建用戶并產(chǎn)生隨機(jī)密碼過(guò)程解析

    這篇文章主要介紹了基于Python新建用戶并產(chǎn)生隨機(jī)密碼過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Python?網(wǎng)易易盾滑塊驗(yàn)證功能的實(shí)現(xiàn)

    Python?網(wǎng)易易盾滑塊驗(yàn)證功能的實(shí)現(xiàn)

    這篇文章主要介紹了Python?網(wǎng)易易盾滑塊驗(yàn)證,主要是借助之前寫阿里云盾滑塊和極驗(yàn)滑塊的經(jīng)驗(yàn)寫的本文,通過(guò)使用selenium請(qǐng)求url,并觸發(fā)滑塊驗(yàn)證,需要的朋友可以參考下
    2022-05-05
  • Python對(duì)列表的操作知識(shí)點(diǎn)詳解

    Python對(duì)列表的操作知識(shí)點(diǎn)詳解

    在本篇文章里小編給大家整理了關(guān)于Python對(duì)列表的操作知識(shí)點(diǎn)總結(jié)以及實(shí)例代碼運(yùn)用,需要的朋友們跟著學(xué)習(xí)下。
    2019-08-08
  • python內(nèi)置函數(shù)zip詳解

    python內(nèi)置函數(shù)zip詳解

    這篇文章主要為大家介紹了python內(nèi)置函數(shù)zip,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-01-01
  • Python實(shí)戰(zhàn)實(shí)現(xiàn)爬取天氣數(shù)據(jù)并完成可視化分析詳解

    Python實(shí)戰(zhàn)實(shí)現(xiàn)爬取天氣數(shù)據(jù)并完成可視化分析詳解

    這篇文章主要和大家分享一個(gè)用Python實(shí)現(xiàn)的小功能:獲取天氣數(shù)據(jù),進(jìn)行可視化分析,帶你直觀了解天氣情況!感興趣的小伙伴可以學(xué)習(xí)一下
    2022-06-06
  • Python中的異常處理詳解

    Python中的異常處理詳解

    這篇文章主要介紹了Python中的異常處理詳解,在編寫Python程序時(shí),經(jīng)常會(huì)遇到各種運(yùn)行時(shí)錯(cuò)誤,這些錯(cuò)誤會(huì)導(dǎo)致程序終止并拋出異常。然而,有時(shí)我們希望程序能優(yōu)雅地處理這些錯(cuò)誤,而不是直接崩潰,這就需要用到異常處理了,需要的朋友可以參考下
    2023-07-07
  • mac下pycharm設(shè)置python版本的圖文教程

    mac下pycharm設(shè)置python版本的圖文教程

    今天小編就為大家分享一篇mac下pycharm設(shè)置python版本的圖文教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • python小數(shù)字符串轉(zhuǎn)數(shù)字的五種方法

    python小數(shù)字符串轉(zhuǎn)數(shù)字的五種方法

    本文主要介紹了python小數(shù)字符串轉(zhuǎn)數(shù)字的五種方法,根據(jù)具體需求選擇合適的方法進(jìn)行小數(shù)字符串轉(zhuǎn)數(shù)字,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-01-01
  • Python樹的序列化與反序列化的實(shí)現(xiàn)

    Python樹的序列化與反序列化的實(shí)現(xiàn)

    在本文中,我們將深入討論如何實(shí)現(xiàn)樹的序列化與反序列化算法,提供Python代碼實(shí)現(xiàn),并詳細(xì)說(shuō)明算法的原理和步驟,感興趣的可以了解一下
    2023-11-11
  • Python 模擬登陸的兩種實(shí)現(xiàn)方法

    Python 模擬登陸的兩種實(shí)現(xiàn)方法

    這篇文章主要介紹了Python 模擬登陸的兩種實(shí)現(xiàn)方法的相關(guān)資料,這里提供兩種方法一個(gè)是普通寫法寫的,另外一個(gè)是基于面向?qū)ο髮懙?,模擬登錄成功后才可能抓取內(nèi)容,需要的朋友可以參考下
    2017-08-08

最新評(píng)論