
Python
敬致知
不患无位,患所以立,不患莫己知,求为可知也。
展开
-
apache2/httpd,静态/动态转发问题。
希望实现访问https://127.0.0.1:8443, 能够默认找到/var/www/static_web下的index.htm页面,同时https://127.0.0.1:8443/api/v1/account/能够直接转发到/api/v1/account/如果是以下配置:Listen 8443<VirtualHost *:8443>WSGIDaemonProcess admin processes=2 threads=15 display-name=admin python-原创 2021-09-18 10:34:58 · 565 阅读 · 0 评论 -
后台进程实现定时任务的原理
timer类,后台运行定义一个方法loop,一个列表timer_task,其中存储定时任务类,包含任务命令,上次执行时间,执行时间间隔等属性;loop一直遍历timer_task,判断现在距上次执行时间是否大于执行时间间隔;特别对于每天定时执行的任务,时间间隔应该计算为 每天定时执行的时刻 距 当天0点 的时间间隔;...原创 2021-09-15 10:34:12 · 462 阅读 · 0 评论 -
OperationalError: (1054, “Unknown column ‘*_id‘ in ‘on clause‘“), 使用db_colnum指定外键字段名
db_constraint=False 参数在Django使用外键,可以不实际在数据中产生约束。例如:class Group(models.Model): id = models.CharField(max_length=50, null=False, primary_key=True)class Device(models.Model): GroupId = models.ForeignKey(to='Group', on_delete=models.CASCADE, db_constrain原创 2021-09-10 19:13:03 · 1192 阅读 · 1 评论 -
Django count和group by顺序问题,解决被自动加入group by主键的问题
django中的数据库查询Model.objects.values('OSPlatform', 'GroupId').annotate( DeviceStatus=F('Status')).annotate(DeviceCount=Count('*'))如果values放在annotate前面,实际上的SQL会按照’OSPlatform’, 'GroupId’这两个字段group by;如果valus放在annotate后面,实际上的SQL只会有默认的grou原创 2021-09-08 11:04:46 · 459 阅读 · 0 评论 -
Django数据库update的错误操作
一User.objects.filter(Id=id_).first()user.Email = emailuser.UpdateTime = datetime.datetime.now()user.save()二user = User.objects.filter(Id=id_).first()user.update(Email=email, UpdateTime=datetime.datetime.now())注意这种更新方式并不能成功,需要直接在User后面加...原创 2021-08-25 11:28:15 · 970 阅读 · 0 评论 -
django.db.utils.ProgrammingError:(1146, “Table * doesn‘t exist“) 原因及其解决办法
原因一:app中migrations文件夹下每次更改产生的记录文件中,有对某张表的删除,或者字段删除操作,但是这些修改是在别人的环境中产生,而在自己的环境是第一次运行,就会在python manage.py migrate的时候先去运行删除操作,这时候就会报错django.db.utils.ProgrammingError: (1146, "Table '表' doesn't exist")原因二:在urls.py文件中有先调用该表。...原创 2021-08-18 16:37:10 · 1617 阅读 · 0 评论 -
Windows调用远程Windows server中的程序(installshield)进行installshield打包
build机器:client有installshield的机器: serverclient发送net use 命令到server,server 运行net use 将client的C盘(build 运行目录)映射为自己的m盘,client 运行build脚本,在脚本中需要用到installshield的时候,发送包含client运行目录(被映射到了M盘)的命令,此命令中的C:需要被替换为m:,server收到命令,并运行。实际的效果是,server调用自己机器上的installshield,对原创 2021-08-12 16:15:58 · 184 阅读 · 0 评论 -
M1芯片Mac,Terminal和Pycharm启动virtualenv的Python2.7环境失败
在Terminal中virtualenv -p=python2.7 envname 创建python2.7的env环境,source activate 启动virtualenv环境之后,输入python启动Python,报错:[1] 28264 killed python2.7在Pycharm中Add Python Interpreter, 选择Base interpreter: /usr/bin/python2.7, 报错:ERROR: The executable Venv/manager/bi原创 2021-07-29 01:25:47 · 646 阅读 · 0 评论 -
Linux访问Windows的共享目录,pysmb(参数remote_name定义)
方案一net start 此命令只在Windows下面可用方案二sudo mount -t cifs -o username=administrator,password=password //remote_share_server_ip/share_dir ./data这条命令必须使用root权限,对于不能使用root权限的应用无法实现。没有sudo会报错:mount: only root can use "--options" option方案三Python包pysmbdef check原创 2021-07-26 23:26:15 · 3209 阅读 · 0 评论 -
Python3在doc string中设置参数和返回值的类型,Pycharm
def foo(param): """ Get update module info in AsmsConfig.ini. :type param: rest_framework.status :rtype: list of UpdateItemInfo """ result = [] info = UpdateItemInfo() result.append() return 在pycharm中能够显示foo()方法的返回值为list[UpdateItemIn原创 2021-06-21 19:39:20 · 400 阅读 · 0 评论 -
Python2中while循环条件改变,能够立刻被监测
"""Only can run in unix, because of module python-daemon==2.3.0"""import osimport signalimport sysimport timeimport daemondef get_asms_engine_pid(): if os.path.exists('/root/test_while_dir/test_pid'): with open('/root/test_while_dir/t原创 2021-05-25 17:30:21 · 283 阅读 · 0 评论 -
Ubuntu编译安装python3.7.10,解决‘_ctypes‘和ssl问题, 建立软链接python3.7和pip3.7
问题1:pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available解决:sudo apt install libssl-dev问题2:ModuleNotFoundError: No module named '_ctypes'解决sudo apt-get install libffi-dev安装步骤:./configure --pr原创 2021-05-19 14:44:16 · 1978 阅读 · 0 评论 -
Python中if if else和 if elif else区别
if if else:执行完第一个if还会去判断下一个if是否满足,不满足则会执行else,即当i==’)’, stack pop弹出之后,还会去执行stack.append()stack = []for i in s: if len(stack)==0: stack.append(i) continue if i==')' and stack[-1]=='(': stack.pop() if i=='}' and stack[-1原创 2021-04-21 13:58:45 · 2097 阅读 · 1 评论 -
Django Rest_Framework 添加分页模块
settings.py 文件中的REST_FRAMEWORK = {}配置中,增加'DEFAULT_PAGINATION_CLASS': 'util.custom_pagination.CustomPagination','PAGE_SIZE': 20,View中return 的data只包含数据列表[data], 会自动添加上分页信息,变成:{ "count": 12, "next": "request url", "previous": null, "re原创 2021-03-25 18:36:48 · 81 阅读 · 0 评论 -
subprocess.Popen获取子程序输出
new_child = subprocess.Popen([self.manage, worker], stderr=subprocess.PIPE)for line in iter(new_child.stderr.readline, ''): logger.debug(line)原创 2021-03-01 18:39:35 · 1437 阅读 · 0 评论 -
Manager(导入django环境, 调用manager里的包)测试自己的代码
需要测试自己写的代码时,需要导入Django的环境分步指南在项目目录下新建base.py, 内容为import osimport sysimport djangohere = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(here)os.environ.setdefault("DJANGO_SETTINGS_MODULE","web_console.settings")djang原创 2021-01-26 20:07:38 · 124 阅读 · 0 评论 -
os.getcwd()获取C编写的python模块的可执行文件工作目录
使用C编写的python模块,因为C的代码需要在其可执行文件同一目录放一个配置文件,但由于项目中python是由做成的httpd.service启动,不能确定实际是从哪里启动的,导致此python模块一直找不到需要的配置文件,而运行失败。解决办法:通过os.getcwd()获取实际的工作目录,再将配置文件放到此位置,最后运行成功。...原创 2020-11-18 17:56:33 · 185 阅读 · 0 评论 -
Django初始化数据库,及已有部分表时重新初始化数据库
一般情况,初始化数据库使用以下命令: python ${CUR_DIR}/manage.py makemigrations python ${CUR_DIR}/manage.py migrate python ${CUR_DIR}/manage.py loaddata initial_data遇到一种情况是,在初始化的时候,数据库偶然断连,导致某些表没有成功创建,此时需要重新初始化,执行以下命令:python manage.py migrate --fake-initialp原创 2020-06-16 10:13:06 · 1410 阅读 · 0 评论 -
Linux 注册的系统服务(service), 调用环境变量的问题
场景在系统服务中注册服务,通过系统服务启动的应用,不能获取已经全局设置的环境变量。已经尝试在以下位置设置了环境变量, HOME_PATH=‘path’:/etc/profile~/.bash_profile~/.bashrc但是,注册的系统服务(service)中的以下命令:# Start main serviceExecStart=HOME_PATH/manage.py run...原创 2020-04-20 15:32:49 · 7133 阅读 · 0 评论 -
Ubuntu安装pyparted, dmidecode过程
通过pip install pyparted 成功,但是依旧提示libparted未安装。 解决方法: 通过apt-get install python-partedpip install dmidecode成功,但是提示没有dmidecode.dmidecodeXML()。 解决方法,pip uninstall dmidecode包,通过apt-get 重新安装...原创 2018-09-09 15:20:57 · 3034 阅读 · 0 评论 -
列表含有子列表展开成一个列表
元素都为列表: listA = [['a'], ['b'], ['c', 'd']] 展开成listA1 = ['a', 'b', 'c', 'd'] 命令: listA1 = sum(listA, []) 因为sum第二个参数的默认值是0, 0不能和列表相加,所以需要加入参数[]元素包含str, 列表等类型: 此时sum方法就不行了。 listB = ['a', ['b'], ...原创 2018-09-09 16:37:41 · 1559 阅读 · 0 评论 -
SQLAlchemy和flask-sqlalchemy中通过数据库映射出model.py文件
SQLAlchemy中使用sqlacodegenflask-sqlalchemy中使用flask-sqlacodegen --flaskflask-sqlalchemy它致力于简化在 Flask 中 SQLAlchemy 的使用,提供了有用的默认值和额外的助手来更简单地完成常见任务。## 自己的代码#!/usr/bin/python# -*- coding: utf-8 -*-...原创 2018-12-09 00:10:49 · 1476 阅读 · 2 评论 -
一行代码获取信息
os.popen( "rpm -qi hyve-testview|grep Version|sed 's/Version[ ]*:[ ]//g'|sed 's/[ ]*Vendor.*//g'" ).read().strip()如果用正则: output = commands.getoutput('rpm -qi hyve-testview') vers...原创 2019-06-14 14:08:18 · 252 阅读 · 0 评论 -
插件Plugin 架构
import importlibimport pkgutilfrom collections import OrderedDictregister_plugins = OrderedDict()def get_all_plugins(print_info=False): """ get all plugins Returns: plugins:...原创 2019-06-28 15:37:05 · 454 阅读 · 0 评论 -
dict的setdefault方法 和 defaultdict(int)
dict.setdefault(key, default=None)key – 查找的键值。default – 键不存在时,设置的默认键值。from collections import defaultdictdict1 = defaultdict(int)不会报keyerror,dict1[‘a’] 会有默认类型int 初始值为0,可以直接dict1[‘a’] += 1...原创 2019-07-10 16:09:58 · 2202 阅读 · 0 评论 -
ansible在本地从remoteA同步(synchronize)文件到remoteB
本地连接的是serverA:hosts: serverB - name: Deploy firmware images synchronize: src: /path/on/serverA dest: /path/on/serverB checksum: true delegate_to: serverB本地连接的是serverB:...原创 2019-08-02 10:23:49 · 2696 阅读 · 0 评论 -
pkgutil.walk_packages
pkgutil.walk_packages(path=path, prefix=name + ‘.’)递归导入次文件所在文件夹中的包for _, modname, ispkg in pkgutil.walk_packages(path=__path__, prefix=__name__ + '.'): if not ispkg: importlib.import_mod...原创 2019-08-20 16:14:15 · 2072 阅读 · 1 评论 -
Django 测试
创建超级用户python ./manage.py createsuperuser --username=bryany --email=bryany@test.comdump数据&插入数据mysqldump -uroot -pvmi@Asiainf0 --all-database > /tmp/all.sqlmysql source /tmp/all.sql;获取用户to...原创 2019-09-19 14:13:45 · 124 阅读 · 0 评论 -
Python中执行MySQL语句, 遇到同时有单引号, 双引号处理方式 !r, repr()
SQL语句:insert_cmd = &amp;amp;quot;INSERT INTO {0} SET {1}&amp;amp;quot;.format(db_conn.firmware_info_table, ','.join(['{0}={1!r}'.format(k, str(v)) for (k, v) in info_dict.items()])){0}={1!r} 中, 设置字段的值,一般情况应该是:columnA='{}...原创 2018-09-09 16:03:42 · 3094 阅读 · 0 评论