编辑
2024-07-08
🧰语言-python
00
请注意,本文编写于 346 天前,最后修改于 225 天前,其中某些信息可能已经过时。

目录

查看包的所有方法
from future import with_statement
print中的f的作用
waitress
flask的代码
启动入口代码
安装依赖包
启动方式
列表的赋值
import的使用
返回值
例子:
python getattr()函数

查看包的所有方法

python
import bottle print(dir(bottle))

from future import with_statement

关于__future__的作用:

  • 为了避免混淆现有工具,分析import 语句和期望找到他们要导入的模块
  • 确保2.1之前的版本导入__future__产生运行时异常,因为2.1之前没有这个模块
  • 记录何时引入了不兼容的更改,以及何时将其强制执行。这是一种可执行文档,可以通过导入__future__进行可编程式检查。

换句话说:

python在新版本会引入新的功能特性,但是有的时候有些改动是不兼容旧版本的,举个例子来说 比如说你的项目是用的py2.7,现在你需要迁移到3.x版本,直接升级到3.x肯定是不行的,那怎么办呢?这个时候就需要使用__future__了。 我们可以通过__future__导入新版本某些模块,测试新版本的新功能,等测试成功后,再升级到新的版本上。

例子: print,使用过py2.7和py3.x的小伙伴肯定都知道,在3.x的时候,print成了一个函数,那么让我们在py2.7通过__future__感受一下:

python
>>from __future__ import print_function >>print <built-in function print>

除了print还有其他不少类似的,详情可以查看官网:

featureeffect中文解释
nested_scopesStatically Nested Scopes嵌套域
generatorsSimple Generators
divisionChanging the Division Operator
absolute_importImports
and Absolute/Relative
with_statementThe "with" statement通过某种方式简化异常处理
print_functionMake print a function
unicode_literalsBytes literals in Python 3000
generator_stopStopIteration Handing insure generators

print中的f的作用

f开头表示在字符串内支持大括号内的python表达式,例如:

python
port = 8888 print(f'Serving HTTP on port {PORT} ...') # 输出结果 Serving HTTP port 8888.....

waitress

部署框架的优点

  • 单文件启动,python3 pss_waitress.py
  • 入口文件可以多次启动,比如多次运行python3 pss_waitress.py,这样的好处是可以把python3 pss_waitress.py加到定时任务,每一分钟运行一次,那么如果进程挂掉了,就会自己启动起来了。
  • 包含日志打印模块,打印到文件,并且会滚动删除

flask的代码

python
import logging from flask import Flask app = Flask(__name__) @app.route('/') def index(): # 这样写日志 logging.info("myendpoint We are computering now") return 'We are computering now' @app.route('/server_status_code') def server_status_code(): """用于探活""" return "ok"

启动入口代码

python
import logging.handlers LOG_FILE = "test_log.log" log_format = "[%(levelname)s] %(asctime)s [%(filename)s:%(lineno)d, %(funcName)s] %(message)s" logging.basicConfig(filename=LOG_FILE, filemode="a", format=log_format, level=logging.INFO) time_hdls = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='D', interval=1, backupCount=7) logging.getLogger().addHandler(time_hdls) logging.info("begin service") import requests from pss_app import app from waitress import serve DEPLOY_PORT = 8889 def process_is_alive(): """检测本地进程是否存在""" try: r = requests.get(f"http://127.0.0.1:{DEPLOY_PORT}/server_status_code") if r.status_code == 200 and r.text == "ok": return True return False except Exception as e: return False if __name__ == "__main__": logging.info("try check and start app, begin") if process_is_alive(): logging.info("process_is_alive_noneed_begin") else: logging.info("process_is_not_alive_begin_new") serve(app, host='0.0.0.0', port=DEPLOY_PORT, threads=30) # WAITRESS! logging.info("try check and start app, end")

安装依赖包

bash
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple flask waitress requests

启动方式

bash
python3 pss_waitress.py

列表的赋值

python
a=['1','2'] frst,secon = a # 输出结果 frst为1 secon为2

__import__的使用

python
module, application = app_path.split(':') module = __import__(module)

import()函数用于动态加载类和函数 如果一个模块经常变化就可以使用__import__()来动态载入,主要用于反射或者延迟加载模块(例如:只在某些时候用模块,所以使用的时候,再导入。) import(module)相当于import module

返回值

返回元组列表

例子:

a.py文件代码

python
#!/usr/bin/env python #encoding: utf-8 import os print ('在 a.py 文件中 %s' % id(os))

test.py 文件代码:

python
#!/usr/bin/env python #encoding: utf-8 import sys __import__('a') # 导入 a.py 模块

输出结果为

在 a.py 文件中 4394716136

python getattr()函数

用于返回一个对象属性值 语法:

getattr(object,name[,default])

参数:

  • object --对象
  • name -- 字符串,对象属性
  • default --默认返回值,如果不提供该参数,在没有对应属性时,将出发Attribute Error
python
>>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a, 'bar') # 获取属性 bar 值 1 >>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'bar2' >>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值 3 >>>

本文作者:Eric

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!