• 学习日记-2019529


    Flask脚本服务搭建、基于上下文环境的处理、Python从列表中随机抽取若干元素、Python中format格式化输出、Python多进程

    【来源】https://www.u3v3.com/

    学习日记 2019/5/29

    Flask脚本服务搭建

    flasky.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    import os
    from dotenv import load_dotenv

    dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
    if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

    COV = None
    if os.environ.get('FLASK_COVERAGE'):
    import coverage
    COV = coverage.coverage(branch=True, include='app/*')
    COV.start()

    import sys
    import click
    from flask_migrate import Migrate, upgrade
    from app import create_app, db
    from app.models import User, Follow, Role, Permission, Post, Comment

    app = create_app(os.getenv('FLASK_CONFIG') or 'default')
    migrate = Migrate(app, db)



    def ():
    return dict(db=db, User=User, Follow=Follow, Role=Role,
    Permission=Permission, Post=Post, Comment=Comment)


    @app.cli.command()
    @click.option('--coverage/--no-coverage', default=False,
    help='Run tests under code coverage.')
    def test(coverage):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
    import subprocess
    os.environ['FLASK_COVERAGE'] = '1'
    sys.exit(subprocess.call(sys.argv))

    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
    COV.stop()
    COV.save()
    print('Coverage Summary:')
    COV.report()
    basedir = os.path.abspath(os.path.dirname(__file__))
    covdir = os.path.join(basedir, 'tmp/coverage')
    COV.html_report(directory=covdir)
    print('HTML version: file://%s/index.html' % covdir)
    COV.erase()


    @app.cli.command()
    @click.option('--length', default=25,
    help='Number of functions to include in the profiler report.')
    @click.option('--profile-dir', default=None,
    help='Directory where profiler data files are saved.')
    def profile(length, profile_dir):
    """Start the application under the code profiler."""
    from werkzeug.contrib.profiler import ProfilerMiddleware
    app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length],
    profile_dir=profile_dir)
    app.run()


    @app.cli.command()
    def deploy():
    """Run deployment tasks."""

    upgrade()

    # create or update user roles
    Role.insert_roles()

    # ensure all users are following themselves
    User.add_self_follows()

    if __name__ == '__main__':
    app.cli()

    运行文件

    python flasky.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    (microvenv) [root@iz2ze8rern8nx1sglo8ub1z microblog]# python flasky.py
    Usage: flasky.py [OPTIONS] COMMAND [ARGS]...

    Options:
    --help Show this message and exit.

    Commands:
    deploy Run deployment tasks.
    profile Start the application under the code...
    test Run the unit tests.#新添加的内容

    python flasky.py test

    1
    2
    3
    4
    5
    6
    7
    (microvenv) [root@iz2ze8rern8nx1sglo8ub1z microblog]# python flasky.py test
    te 大专栏  学习日记-2019529st_password_setter (test_user_model.UserModelTestCase) ... ok

    ----------------------------------------------------------------------
    Ran 1 test in 0.447s

    OK

    基于上下文环境的处理

    在 create_app内做Flask相关的初始化,将这部分资源处理置于独立的模块中, 使用的时候直接引入, 在模块第一次引入的时候就完成了资源的连接处理, 但总有一些还是需要运行前要执行的内容, 比如应用参数设置。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    if app.config['SSL_REDIRECT']:
    from flask_sslify import SSLify
    sslify = SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')

    return app

    Python从列表中随机抽取若干元素

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import random
    x = [283,238,46,57,82,976]
    random.choice(x)
    random.sample(x,3)
    #从某个范围内获取若干个
    random.sample(range(100000),30)
    #选取随机字符
    random.choice('abcdrfgsfffgr')
    #生成随机整数
    random.randint(100,200)
    #生成随机偶数
    random.randrange(0,99,2)
    #生成0-1随机浮点数
    random.random()

    Python中format格式化输出

    通过key名填充字符

    1
    print('My Name is {name},Age is {age}'.format(name=name,age=age))

    通过字典的方式作参数传递

    1
    2
    params = {'name':name,'age':age}
    print('My Name is {name},Age is {age}'.format(**params))

    将tuple作为可变参数传递特性

    1
    2
    params=('Tony',18)
    print('My Name is {0},Age is {1},And Your Age is {1}'.format(*params))

    字符对齐

    1
    2
    3
    print('{:>10},{:>10}'.format('tony',18))#左对齐
    #右对齐<
    #居中对齐^

    数字格式化

    1
    2
    3
    4
    5
    6
    7
    #十进制转
    #二进制
    print('{:b}'.format(x))
    #八进制
    print('{:o}'.format(x))
    #十六进制
    print('{:x}'.format(x))

    浮点数精度控制

    1
    2
    pi = 3.1415926
    print('{:.2f}'.format(pi))#保留两位小数3.14

    三层{}可以转义

    1
    print('{{{0:.2f}}}'.format(pi))#{3.14}

    Python多进程

    • 进程创建

    unix下使用fork方式创建子进程

    1
    2
    3
    4
    Process 24896 start ... 
    This is Father process,And Its child pid is 24897
    This is child process and my pid is 24897,my father process is 1
    #子进程fork的结果总是0,可以用来作为区分父子进程的标志

    变量在多进程之间并没有什么影响

    windows下实现多进程用到了multiprocessing

    pro = Process(target=pro_do,args=("test","dev"))

    pro.start()

    是否阻塞方式执行,如果有则阻塞,否则非阻塞

    pro.join()

    可以通过Pool进程池创建多个进程,可以指定启动的子进程数量

    • 进程间通信

    父进程可以指定子进程执行的方法及参数,达到父进程向子进程单项通信

    子进程可以通过Queue方式向父进程通信write_queueread_queue

    两个进程间的通信可以使用Pipe形式send_piperecv_pipe

  • 相关阅读:
    实验七:类的多态性
    实验六:类的封装(P105 3-35)
    实验五:任意输入10个int类型数据,排序输出,再找出素数
    第三周学习总结
    hbase对Java的简单操作
    hbase的shell命令
    需求工程3
    需求工程2
    软件需求1
    认识软件需求
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12046682.html
Copyright © 2020-2023  润新知