Category Archives: Python

Python openpyxl excel open zipfile error resolution: zipfile.BadZipFile: File is not a zip file

Error description

The immediate cause of the error is trying to open a table file that was not previously closed. This error could be caused by:

In the process before

  • the workbook that was opened did not have a normal close, resulting in additional temporary files, and errors occurred when trying to open these temporary files; The workbook before
  • did not overwrite the existing files when saving.

can also be other errors, but it doesn’t matter, look at the solution, you can from the root to avoid this kind of error about load/save .

solution

open and exit excel files in a safe way, you can avoid the above type of load/save error. When opening a file, open excel in the following ways: if the original file already exists, just load it directly; If it doesn’t exist, create a new workbook and prepare the last save.

import os
from openpyxl import Workbook
from openpyxl import load_workbook
if os.path.exists(new_filename):
    new_wb = load_workbook(new_filename)
else:
    new_wb = Workbook()

is safely saved as excel

  • first, remember to exit as soon as you run out of files. Second, when exiting a file, for all workbooks, if you need to save, if you don’t need to save (read-only), be sure to close
wb.save(filename) # For workbooks that need to save written content
wb.close() # Read-only workbook for the program

[Python] error in installing jupyter: defaulting to user installation because normal Requirement already satisfied

when installing jupyter, it appears as

Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: jupyter in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (1.0.0)
Requirement already satisfied: ipywidgets in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (7.5.1)
Requirement already satisfied: notebook in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (6.1.4)
Requirement already satisfied: nbconvert in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (6.0.4)
Requirement already satisfied: ipykernel in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (5.3.4)
Requirement already satisfied: qtconsole in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (4.7.7)
Requirement already satisfied: jupyter-console in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter) (6.2.0)
Requirement already satisfied: nbformat>=4.2.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipywidgets->jupyter) (5.0.7)
Requirement already satisfied: traitlets>=4.3.1 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipywidgets->jupyter) (5.0.4)
Requirement already satisfied: ipython>=4.0.0; python_version >= "3.3" in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipywidgets->jupyter) (7.18.1)
Requirement already satisfied: widgetsnbextension~=3.5.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipywidgets->jupyter) (3.5.1)
Requirement already satisfied: jupyter-core>=4.6.1 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (4.6.3)
Requirement already satisfied: prometheus-client in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (0.8.0)
Requirement already satisfied: terminado>=0.8.3 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (0.9.1)
Requirement already satisfied: argon2-cffi in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (20.1.0)
Requirement already satisfied: ipython-genutils in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (0.2.0)
Requirement already satisfied: jupyter-client>=5.3.4 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (6.1.7)
Requirement already satisfied: tornado>=5.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (6.0.4)
Requirement already satisfied: jinja2 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (2.11.2)
Requirement already satisfied: Send2Trash in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (1.5.0)
Requirement already satisfied: pyzmq>=17 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from notebook->jupyter) (19.0.2)
Requirement already satisfied: bleach in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (3.2.1)
Requirement already satisfied: pygments>=2.4.1 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (2.7.1)
Requirement already satisfied: jupyterlab-pygments in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.1.1)
Requirement already satisfied: pandocfilters>=1.4.1 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (1.4.2)
Requirement already satisfied: entrypoints>=0.2.2 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.3)
Requirement already satisfied: nbclient<0.6.0,>=0.5.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.5.0)
Requirement already satisfied: mistune<2,>=0.8.1 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.8.4)
Requirement already satisfied: testpath in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.4.4)
Requirement already satisfied: defusedxml in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbconvert->jupyter) (0.6.0)
Requirement already satisfied: qtpy in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from qtconsole->jupyter) (1.9.0)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter-console->jupyter) (3.0.7)
Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbformat>=4.2.0->ipywidgets->jupyter) (3.2.0)
Requirement already satisfied: colorama; sys_platform == "win32" in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.4.3)
Requirement already satisfied: pickleshare in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.7.5)
Requirement already satisfied: jedi>=0.10 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.17.2)
Requirement already satisfied: backcall in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.2.0)
Requirement already satisfied: decorator in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (4.4.2)
Requirement already satisfied: setuptools>=18.5 in c:\program files (x86)\microsoft visual studio\shared\python37_64\lib\site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (40.8.0)
Requirement already satisfied: pywin32>=1.0; sys_platform == "win32" in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jupyter-core>=4.6.1->notebook->jupyter) (228)
Requirement already satisfied: pywinpty>=0.5; os_name == "nt" in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from terminado>=0.8.3->notebook->jupyter) (0.5.7)
Requirement already satisfied: cffi>=1.0.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from argon2-cffi->notebook->jupyter) (1.14.2)
Requirement already satisfied: six in c:\program files (x86)\microsoft visual studio\shared\python37_64\lib\site-packages (from argon2-cffi->notebook->jupyter) (1.15.0)
Requirement already satisfied: python-dateutil>=2.1 in c:\program files (x86)\microsoft visual studio\shared\python37_64\lib\site-packages (from jupyter-client>=5.3.4->notebook->jupyter) (2.8.1)
Requirement already satisfied: MarkupSafe>=0.23 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jinja2->notebook->jupyter) (1.1.1)
Requirement already satisfied: packaging in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from bleach->nbconvert->jupyter) (20.4)
Requirement already satisfied: webencodings in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from bleach->nbconvert->jupyter) (0.5.1)
Requirement already satisfied: nest-asyncio in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->jupyter) (1.4.0)
Requirement already satisfied: async-generator in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from nbclient<0.6.0,>=0.5.0->nbconvert->jupyter) (1.10)
Requirement already satisfied: wcwidth in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->jupyter-console->jupyter) (0.2.5)
Requirement already satisfied: pyrsistent>=0.14.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets->jupyter) (0.17.3)
Requirement already satisfied: attrs>=17.4.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets->jupyter) (20.2.0)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets->jupyter) (1.7.0)
Requirement already satisfied: parso<0.8.0,>=0.7.0 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= "3.3"->ipywidgets->jupyter) (0.7.1)
Requirement already satisfied: pycparser in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from cffi>=1.0.0->argon2-cffi->notebook->jupyter) (2.20)
Requirement already satisfied: pyparsing>=2.0.2 in c:\program files (x86)\microsoft visual studio\shared\python37_64\lib\site-packages (from packaging->bleach->nbconvert->jupyter) (2.4.7)
Requirement already satisfied: zipp>=0.5 in c:\users\shebin xu\appdata\roaming\python\python37\site-packages (from importlib-metadata; python_version < "3.8"->jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets->jupyter) (3.1.0)

according to the way on the Internet, can’t solve
later find jupyter in the user -> appdata-> … -> Python_37 and PIP is in a different folder because it was originally installed in Visual Code and CMD calls in the Visual Code installation directory.

solution:
1, according to the requirement already following the address to find the jupyter installation directory, double-click jupyter-notebook. Exe
2, or directly copy jupyter related files to the original directory, it can be called in the CMD.

Python raspberry pie starts sending IP address to mailbox

#/bin/env python
# -*-coding:utf8-*-
import socket
import fcntl
import time
import struct
import smtplib
import urllib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
 
 
#发送邮件的基本函数,参数依次如下
# smtp服务器地址、邮箱用户名,邮箱秘密,发件人地址,收件人地址(列表的方式),邮件主题,邮件html内容
def sendEmail(smtpserver, username, password, sender, receiver, subject, msghtml):
  msgRoot = MIMEMultipart('related')
  msgRoot["To"] = ','.join(receiver)
  msgRoot["From"] = sender
  msgRoot['Subject'] =  subject
  msgText = MIMEText(msghtml,'html','utf-8')
  msgRoot.attach(msgText)
  #sendEmail
  smtp = smtplib.SMTP()
  smtp.connect(smtpserver)
  smtp.login(username, password)
  smtp.sendmail(sender, receiver, msgRoot.as_string())
  smtp.quit()
 
 
# 检查网络连同性
def check_network():
  # 试验5次ping 百度,如果连通就返回True,否则返回False
  for i in range(0, 5):
    try:
      result=urllib.urlopen('http://baidu.com').read()
      #print result
      print "Network is Ready!"
      break
    except Exception , e:
      print e
      print "Network is not ready,Sleep 5s...."
      time.sleep(5)
  else:
    print "Sorry that pi isn't connectted to Internet now"
    return False
  return True
 
 
# 获得本级制定接口的ip地址
def get_ip_address():
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  s.connect(("1.1.1.1",80))
  ipaddr=s.getsockname()[0]
  s.close()
  return ipaddr
 
 
if __name__ == '__main__':
  if check_network():
    ipaddr = get_ip_address()
    now = datetime.datetime.now()
    time_info = now.strftime('%Y-%m-%d %A %H:%M:%S')
    send_text = "Boot time: %s\nIP addr: %s" % (time_info, ipaddr)
    sendEmail('smtp.sina.com','you email username ','your email password ','your emial address',['[email protected]'], 'Raspberry Pi boot status', send_text)
  else:
    print "Sorry that I can't help without network"

 

Python: How to get the size of the picture (byte/kb/mb)

local image

from urllib import request
from PIL import Image
import os
import numpy as np
import requests,io

dirpath = r"E:\图片集\0\图片大小"
filenames = os.listdir(dirpath)

for filename in filenames[:]:
    portion = os.path.splitext(filename)  # 将文件名和缀名分成俩部分
    filepath = os.path.join(dirpath, filename)

    with open(filepath, "rb") as f:
        size = len(f.read())
        print("{}图片的大小{} byte,{} kb,{} Mb".format(filename,size, size/1e3, size/1e6))

results:

image url </ strong> </ p>

import requests,io

urls = ['http://******/image/0826/2411kb.png',
        'http://******/image/0826/2026kb.png',
        'http://******/image/0826/1968kb.png']
for url in urls:
    image = requests.get(url).content
    image_b = io.BytesIO(image).read()
    size = len(image_b)
    print("{}的大小{} byte,{} kb,{} Mb".format(url,size, size/1e3, size/1e6))

results:

Note: as can be seen from the above screenshot, byte/ KB /Mb values obtained from both the local image fetch size and url fetch size are larger than those seen on the computer. I don’t know why, but if anyone knows, please help to solve </p b>

Parallel processing in Python (Pool.map(), Pool.starmap(), Pool.apply ())

1. Parallel processing

parallel processing is a mode of operation in which tasks are run simultaneously in multiple processors on the same computer. The purpose of this mode of work is to reduce the total task processing time, but there is an additional overhead associated with communicating between processes, so for small tasks, the total task time increases rather than decreases.

in the Python language, the multiprocessing module runs a separate parallel process by using child processes instead of threads. It allows you to take advantage of multiple processors on your machine (Windows and Unix), that is, multiple processes can run

in memory completely independently

2. How many parallel processing can your device do at most

the maximum number of processes that can be run at one time is limited by the number of processors in the computer. You can use the cpu_count() function in the multiprocessing module to display

import multiprocessing as mp

print("Number of processers: ", mp.cpu_count())

like my computer only has four:

3. Execute synchronously and asynchronously </h3 b> In

parallel processing, there are two types of execution: synchronous and asynchronous

synchronous execution means that each process completes in the order in which it was started. This is done by locking the main program until the corresponding process has finished executing.

asynchronous execution , in other words, the execution of a process does not involve locking, and as a result, the order in which the process results are returned may be confusing, but in general, asynchronous execution completes faster.

There are two objects in the

multiprocessing module to implement parallel function execution: Pool class and Process class

</ strong>

</ p>

4. Practical problem solving example: calculate the number of elements </h3 b> within a given numerical range in each row

given a two-dimensional matrix (or list and multidimensional list), calculate the number of elements

within a given numerical range in each row

import numpy as np
from time import time

# RandomState()是一个伪随机数生成器
np.random.RandomState(100)
# 0, 10 : 生成0到10的随机整数
# size=[200000, 5]  即生成200000行,一列的 ndarray(二维矩阵的形式,每个里面5个元素)
arr = np.random.randint(0, 10, size=[200000, 5])
data = arr.tolist()  # 将numpy.ndarray 转化为list
# 因为是随机的,所以每次的数字不确定
data = data[:5]
print("数据为:", data)

"""
运行结果:
数据为: [[5, 6, 7, 0, 9], [4, 0, 6, 7, 4], [7, 3, 8, 3, 9], [2, 1, 9, 3, 2], [0, 0, 9, 5, 2]]


"""

4.1 </ strong> don’t use parallel processing reference code </ strong> </ p>
The

function howmany_within_range() is repeated to check howmany diseases the number in the range has returned a count

"""不使用并行处理"""

def howmany_within_range(row, minimum, maximum):
    count = 0
    for n in row:
        if minimum <= n <= maximum:
            count += 1
    return count


result = []
for row in data:
    result.append(howmany_within_range(row, minimum=4, maximum=8))
print("给定数值范围中的元素个数:", result[:10])
"""
注意:以下只是参考输出,因为输入序列是随机的,每次输出结果并不固定
运行结果:
给定数值范围中的元素 [3, 2, 3, 4, 2, 3, 3, 2, 2, 2]
"""

4.2 parallelize the function

The usual way to parallelize code is to take a specific function that can be run multiple times, put it on a different processor, and run it. To do this, you need to use the Pool class to initialize the number of n processors, and then pass the function you want to run and run to the parallel method in the Pool class.

The apply(), map() and starmap() methods are provided in the Pool() to run the passed functions in parallel.

What’s the difference between

apply() and map()?

apply() and map() both take the function to be parallelized as the main parameter, but the difference is that apply() takes the args parameter, which passes each parameter to the function to be parallelized, while map takes only one iterator as the parameter.

Therefore, it is better to use map() for simple, iterative operations for parallel processing, and for faster completion of work

2 Pool. The apply () for parallel processing </ strong> </ p>

if __name__ == '__main__':

    # 1.初始化 multiprocessing.Pool()
    pool = mp.Pool(mp.cpu_count())

    # 2.使用apply(), 将函数howmany_within_range作为主参传进去
    results = [pool.apply(howmany_within_range, args=(row, 4, 8)) for row in data]

    # 3. 不要忘记关闭进程
    pool.close()

    print(results[:10])

note: </ strong> use if __name__ = = “__main__ ‘: put your code in the following to perform, or complains </ p>

The freeze_support “()” line can be omitted if The program
is not going to be frozen to produce an executable. </ p>

if we print outside of this program, we’ll see that it’s going to run in parallel, so we’ll print outside of this program </p b> multiple times

4.2.2 Parallelizing using the Pool. The map () </ strong> </ p>

pool.map () takes only one iterator argument. A simple change to howmany_within_range() is to howmany_within_range_rowonly(), which sets the minimum and maximum to fixed values, that is, . Accepting only the row data list iterator as input is not the best approach, but it clearly shows how it differs from apply()

import multiprocessing as mp
    
    def howmany_within_range_rowonly(row, minimum=4, maximum=8):
        count = 0
        for n in row:
            if minimum <= n <= maximum:
                count += 1
        return count
    
    pool = mp.Pool(mp.cpu_count())
    results = pool.map(howmany_within_range_rowonly,[row for row in data])
    pool.close()
    print(results[:10])

holdings using the Pool. The starmap to parallelize () </ strong> </ p>

, like pool.map (), pool.starmap () takes only one iterator argument, but in starmap() each element in the iterator is also an iterator. This internal iterator allows you to pass arguments to the parallelized function and unwrap them sequentially at execution time, as long as they are passed and unwrapped in the same order

actually, pool. starmap() is like a pool. map() version

that takes arguments

    import multiprocessing as mp

    pool = mp.Pool(mp.cpu_count())
    results = pool.starmap(howmany_within_range, [(row, 4, 8) for row in data])
    pool.close()
    print(results[:10])

5. Asynchronous parallel processing </h3 b>

and synchronous parallel processing peer asynchronous parallel processing functions apply_async(), map_async(), and starmap_async() allow parallel execution of processes asynchronously, that is, the next process can be started as soon as the previous one completes, regardless of the order in which it was started. Therefore, there is no guarantee that the result will be in the same order as the input

6. The use of the Pool. Apply_async to parallelize () </ strong> </ p>

keep updating

</ p>

ModuleNotFoundError: No module named ‘tensorflow.python’ And the pits encountered after installation

error
ModuleNotFoundError: No module named 'tensorflow.python'

after we installed tensorflow, we thought we had debuggable the environment and PIP install tensorflow, if

is entered in CMD

import tensorflow

(normally installed the GPU version tensorflow) :

but may be submitted to the above error, on the Internet a lot according to the results there is no use, 😂 is outrageous.
reason (personal summary) : the computer installed multiple python environment, not only the environment, but also anconda, etc., constitute the virtual environment, so you will encounter various problems when using the command conda to assemble the tensflow environment.
the solution: delete other environment, if you remove after the computer did not have the python environment, then reinstall it again, because I have more than one person has them around, “reshipment can solve the problem of ninety-nine percent”, but if pycharm with few words, I do not recommend to assemble anconda, unloading directly, in python’s official website to download the new version of python. After that, tensorFlow is assembled in the whole large Python environment; With the PIP command, there is little problem with reloading.

after installed, we can run the minist a piece of code: </ p>

from tensorflow.examples.tutorials.mnist import input_data

#加载数据集,参数为下载的路径,如果该路径下没有数据集的话,则会从网上自动下载。
#read_data_sets函数
mnist = input_data.read_data_sets("E:\\桌面\\datatest")
# 打印训练数据大小
print("Training data size:", mnist.train.num_examples)
# 打印验证集大小
print("Validating data size:", mnist.validation.num_examples)
# 打印测试集大小
print("Testing data size:", mnist.test.num_examples)
# 打印训练样例
print("Example training data", mnist.train.images[0])
# 打印训练样例的标签
print("Example training data label:", mnist.train.labels[0])

When

, ninety-nine percent of the time will error and remind:

ModuleNotFoundError: No module named 'tensorflow.tutorials'

We first enter the installation environment of tensorflow, and we can find the installation path

through python’s path method

import tensorflow as tf
print(tf.__path__)

after entering python environment, type the command and get the path, and then find the path of files
(about) the new version of the tensflow

enter the examples of the first file,
there should be no my red line mark.
portal
go here to download, then copy in the directory, if it is the old version, find the examples file, the effect is the same, after found on the Internet part of the introduction code may also have problems. Note that we must refer to pylab with

from matplotlib import pylab

so, when you’re done, you can run the following code.
1.

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
print ( ' 输入数据:', mnist.train.images)
print ( ' 输入数据打shape :', mnist.train.images.shape)
from matplotlib import pylab
im = mnist.train.images[1]
im = im.reshape(-1 ,28)
pylab.imshow(im)
pylab.show()
  • note that our read_data_sets should never be interrupted when downloading data. If they are interrupted, they will report an error if they continue executing later. At this time, either change the path to download again, or find the original download path, delete it and run again.

TypeError: Decimal type object is not a JSON serialization solution

The data type calculated when python connects to a database using select sum(a) from b is Decimal. But this format doesn’t fit the json format, so we can cast the data we get. Convert to an integer, and you’ll be able to fit the JSON format.

@app.route('/c1')
def get_cl_data():
    data = utils.get_conn()
    # data = json.dumps({"confirm": data[0], "suspect": data[1], "heal": data[2], "dead": data[3]})
    # print(data)
    return jsonify({"confirm": int(data[0]), "suspect": int(data[1]), "heal": int(data[2]), "dead": int(data[3])})

</ div>

Python exports the gitlab project

Python export gitlab project

  1. install python-gitlab module
    pip install python-gitlab
    python3 
    pip3 install python-gitlab
    
  2. gitlab application API access token
    path User Settings -> Access Tokens
  3. configure pythongitlab.cfg and place

    in the same directory

    [global]
     default = username
     ssh_verify = False
     timeout = 8
    
     [username]
     url = https://gitlab.com
     private_token = xxxxxxxxxxxx
    

     

    对于API v4使用url https://gitlab.com,如果您使用API v3使用url
    https://gitlab.example.com

    </引用>

      <>

 

import gitlab
gl = gitlab.Gitlab.from_config('username', ['python-gitlab.cfg'])
projects = gl.projects.list()
print(projects)
  • or use the following code to get the group project
    import gitlab
    class GitlabAPI(object):
    	
        def __init__(self, *args, **kwargs):
            self.gl = gitlab.Gitlab('https://gitlab.com', private_token='xxxxxxxxxxxxx', api_version='4')
    
        # 可行 先获取所有group ID, 然后根据group ID 获取项目地址
        def get_all_group(self):
            return self.gl.groups.list(all=True)
        def get_group_by_id(self, groupID):
            group = self.gl.groups.get(groupID)
            projects = group.projects.list(all=True)
            result_list = []
            for project in projects:
                result_list.append(project.http_url_to_repo)
            return result_list
    
    	
    apiObject = GitlabAPI()
    groupProjects = apiObject.get_group_by_id(填写获取到的groupID)
    print(groupProjects)
    

Django Issues: TypeError: “Settings” object is irreversible

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "D:\Python37\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\management\commands\runserver.py", line 138, in inner_run
    handler = self.get_handler(*args, **options)
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super().get_handler(*args, **options)
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\management\commands\runserver.py", line 65, in get_handler
    return get_internal_wsgi_application()
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application
    return import_string(app_path)
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "D:\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\PyCharm\py_place\djangoSimpleproProject1\djangoSimpleproProject1\wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application
    return WSGIHandler()
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__
    self.load_middleware()
  File "D:\PyCharm\py_place\djangoSimpleproProject1\venv\lib\site-packages\django\core\handlers\base.py", line 39, in load_middleware
    for middleware_path in reversed(settings.MIDDLEWARE):
TypeError: 'set' object is not reversible

focus:

TypeError: 'set' object is not reversible

solution:
in setting. Py, change {} of
to []……
problem is, I haven’t changed
and I’m confused, I’ve seen a lot of big guys’ methods, it’s really just this emmmmmmmmmm
and I can’t figure out

Conscience installation: How To install Pyinstaller offline on Windows

could not install the Pyinstaller package online, so I downloaded the Pyinstaller offline package.

need to rely on package, download links: https://download.csdn.net/download/ryanji/12881427: </ p>

  1. pywin32_ctypes
  2. pefile
  3. future
  4. altgraph

installation order is as follows:

  1. altgraph
  2. pywin32_ctypes
  3. future
  4. pefile
  5. pyinstaller

</ p>

Python + Requests +Excel+Jenkins interface automation

python+requests+Excel+Jenkins interface automation

summary most people do interface automation process, found that basically is: python + requests do interface requests; Excel is used to store use cases; HTMLTestRunner generates test reports; Jenkins completes scheduled tasks.

actually takes only a fraction of the time to complete this process, with most of the time wasted in setting up the environment and writing use cases. Here I’m going to write down some of the problems.

interface request
(1) configuration request method: get and post method simple packaging, header parameter setting

# _*_coding:utf-8 _*
import requests

#get请求
def get(url,querystring):
    headers = requestHeader()
    response = requests.request("GET", url, headers=headers, params=querystring)
    # print response.url
    return response

#post请求
def post(url,payload,querystring):
    headers = requestHeader()
    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
    # print response.url
    return response

#设置请求的header
def requestHeader():
    headers = {
    'Content-Type': "application/json",
    'Cache-Control': "no-cache"
    }
    return headers

(2) for the body of a post request, we used a “dict” in text at the beginning, but it always returned “error”. After that, postman used to debug and directly copied the body reference that had been converted into json to make the request, and it worked.

WechatIMG12.jpeg

can be used to convert some problematic bodies in this way.

Another way to convert

(3) body to json: through ast module for conversion (recommended)

import ast
caseParams      =   ast.literal_eval(caseParams)

(4) get use case Excel

through openpyxl module

#用例名
caseName    =   caseFile.getCellVaule(ws,rowIndex,1)
#url
caseUrl     =   caseFile.getCellVaule(ws,rowIndex,3)
#请求方式
caseMethod  =   caseFile.getCellVaule(ws,rowIndex,4)
#参数
caseParams  =   caseFile.getCellVaule(ws,rowIndex,5)

note: in the process of obtaining the use case information, some parameters need to be fault-tolerant
A: whether there are parameters, if there are no parameters, need to pass null;
B: get parameter and post body need to be handled separately:
get parameter is ‘& Param ‘in the form of clear text spliced in the URL;

#将请求参数转换为json格式
caseParams  =   ast.literal_eval(caseParams)
keys        =   dict(caseParams).keys()
values      =   dict(caseParams).values()
for x in xrange(0,len(keys)):
  tempQuery[keys[x]] = values[x]

, the body of the post needs to be put in dict;

caseParams      =   ast.literal_eval(caseParams)

(5) split the required parameters and write the result to the file

#请求返回的内容,转换为json格式
text            =   json.loads(response.text)
                caseFile.setCellValue(ws,rowIndex,6,response.text)

#URL请求耗时
spendTime       =   response.elapsed.total_seconds()
                caseFile.setCellValue(ws,rowIndex,7,spendTime)

#请求结果状态
statue          =   response.status_code
                caseFile.setCellValue(ws,rowIndex,8,statue)
self.assertEqual(statue, 200)

(6) writes the result of the request to an HTML file and displays

WechatIMG13.jpeg

(7) is configured to Jenkins to periodically execute the accessibility of the view interface

learning Python address: https://ke.qq.com/course/2707042?flowToken=1025648

if there are any problems you for learning Python, learning methods, learning course, how to learn efficiently, can be consulting me at any time, or the lack of system study materials, I do this year longer, they think is experienced, can help everyone puts forward constructive Suggestions, this is my Python communication qun: 785128166, if you have any question can be consulting me at any time.