current position：Home>Python development foundation summary (VII) database + FTP + character coding + source code security
Python development foundation summary (VII) database + FTP + character coding + source code security
2022-01-31 15:10:38 【zhulin1028】
「 This is my participation 11 The fourth of the yuegengwen challenge 15 God , Check out the activity details ：2021 One last more challenge 」
One 、 Use of database
1、 Used by fields in the database utf8 Format encoding , But it's a question mark . This problem can be solved by specifying the coding method when querying , Just execute sql sentence ：Query_Execsql(pdb, "SET NAMES 'utf8'");
Be careful , This needs to be done immediately after the connection . also , In other operations , Will always use this code . Unless changed again .
2、fetchone()： Return a record .fetchall()： Return all records .
3、 You can use a simple method to get all the records ：
for tel, name, pwd in cur:
print tel, name, pwd
Two 、FTP Use
Python The standard module of ftplib You can support FTP.
Several functions ：
FTP(host= '' , user= '' , passwd= '' , acct= '' , timeout=_GLOBAL_DEFAULT_TIMEOUT)： If there is user, be Connect(); If there is also user, be login(). If you don't use these parameters , Call yourself after connect and login.
connect(self, host='', port=0, timeout=-999): If the port is not a standard port , You need to call... Manually connect.
login(user = '', passwd = '', acct = ''): land .
pwd(): Get the current working path .
cwd(path): Change the current working path .
dir(path,cb): Display the contents of the directory .cb Is the processing function of the file . Will pass to retrlines. This function can get all the contents of a directory .
retrlines(self, cmd, callback = None): Download Text File .cmd In the form of “RETR FILENAME”,callback It's a function , To process each line of a text file . Here's a question , If you use it directly file Of write Method , Will lose the newline . And there is no writeline function .
retrbinary(self, cmd, callback, blocksize=8192, rest=None): Download binaries ,cmd In the form of “RETR FILENAME”,callback It's a function , To process every block of a text file . Default size 8k, But you can change .
storlines(self, cmd, fp, callback=None): Upload text files .cmd In the form of “STOR FILENAME”.fp It's a file object , There has to be readline Method .callback： Each line transmitted , I'll call this function .
storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None): Upload binaries .cmd In the form of “STOR FILENAME”.fp It's a file object , There has to be read(num_bytes) Method . Default size 8k, But you can change .
quit(): sign out .
3、 ... and 、 The use of character encoding
encode Yes, it will Unicode Turn into str,decode Is to convert a string to Unicode. therefore , To convert a string to another format, you can ：
s = ‘ chinese ’ s.decode(fromcodec).encode(tocodec) Copy code
It can also be used directly ：s.encode(tocodec). This is the time , It is equivalent to calling... By default decode, And the default encoding method is used .
Four 、 Source code security
Python If the code is released directly , May expose the source code .
One way is to use c Expand Python, To replace the core module .
Another compromise is to compile the source code , Generate pyc perhaps pyo file . These things are bytecode files . May be decompiled . therefore , You may need to study Python Of pyo Generation and loading methods , To generate safer Python Bytecode . The Internet says it can be modified Python Source code opcode. Not studied .
command ：python -m compileall .
It can also be in Python Use in ：
import compileall compileall._dir('Lib/', force=True) # Perform same compilation, excluding files in .svn directories. import re compileall._dir('Lib/', rx=re.compile('/[.]svn'), force=True) Copy code
author[zhulin1028],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Django (make an epidemic data report)
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert（python）
guess what you like
leetcode 2062. Count Vowel Substrings of a String（python）
Analysis of Matplotlib module of Python visualization
Django permission management
Python integrated programming -- visual hot search list and new epidemic situation map
[Python data collection] scripy realizes picture download
Python interface automation test framework (basic part) -- loop statement of process control for & while
Daily python, Chapter 9, while loop
Van * Python | save the crawled data with docx and PDF
Five life saving Python tips
Django frequency control
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence（python）
- leetcode 2027. Minimum Moves to Convert String（python）
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph（python）
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores（python）
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching
- Python crawls the map of Gaode and the weather conditions of each city
- leetcode 1275. Find Winner on a Tic Tac Toe Game（python）
- leetcode 2016. Maximum Difference Between Increasing Elements（python）
- Run through Python date and time processing (Part 2)
- Application of urllib package in Python
- Django API Version (II)
- Python utility module playsound
- Database addition, deletion, modification and query of Python Sqlalchemy basic operation
- Tiobe November programming language ranking: Python surpasses C language to become the first! PHP is about to fall out of the top ten?
- Learn how to use opencv and python to realize face recognition!
- Using OpenCV and python to identify credit card numbers
- Principle of Python Apriori algorithm (11)
- Python AI steals your voice in 5 seconds
- A glance at Python's file processing (Part 1)
- Python cloud cat
- Python crawler actual combat, pyecharts module, python data analysis tells you which goods are popular on free fish~
- Using pandas to implement SQL group_ concat
- How IOS developers learn Python Programming 8 - set type 3
- windows10+apache2. 4 + Django deployment
- Django parser