


Python sample code for regularly modifying the database_python
This article mainly introduces the sample code for regularly modifying the database in python. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
When we need to modify the database regularly, we usually choose to start a scheduled process to modify the database. If this kind of scheduled task is written into the business and written as an interface, the scheduled process seems a bit inappropriate? If you need to modify the database 100 times regularly, the conventional method will start 100 processes. Although this process is very lightweight, it still feels uncomfortable. In fact, we can use threading.Timer to create corresponding threads to perform library modification operations, and the idea is relatively simple.
1. Pass in update_time, the time when the database modification operation is performed, and use the subtraction method between update_time and the current time to get the time_delay until the database modification operation. To find the time difference between two standard time format strings, you can use datetime.datetime.strptime() to format the time. The formatted time can be directly subtracted, and the result can be converted into seconds by executing .seconds()
2. Encapsulate the library modification operation into the method update(), and then pass the update and time difference into the thread created by threading.Timer. The usage is created by threading.Timer(interval, function, args=[], kwargs={}) Thread instance, interval is the delay execution time, the unit is seconds, and then start() is executed. Timer is non-blocking and can create multiple threads without affecting each other.
The code is as follows
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from model import Table from handler.base_handler import BaseHandler from threading import Timer import datetime class TimeHandler(BaseHandler): def do_action(self): update_time = "2018-04-07 18:00:00" ads_id = "test_1" t_online = datetime.datetime.strptime(update_time, '%Y-%m-%d %H:%M:%S') now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') t_now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S') time_delay = (t_online - t_now).seconds t1 = Timer(time_delay, self.update, (ads_id, )) t1.start() self.result = "success" return def update(self, ads_id): self.db.dsp.query(Table).filter(Table.ads_id == ads_id).update({Table.is_del: 0}) self.db.dsp.commit()
You can change update_time to the parameter passed in by the front end, and it can be executed at that time The database operation has been changed. I encountered a small pitfall at that time, that is, the database modification operation did not take effect because the commit() in the last line was not added. Originally, the commit to change the library was written in the base class BaseHandler to take effect, but the update() here is executed in the Timer thread, which is an asynchronous operation. Commit() needs to be executed in the thread to make the changes effective.
This method of timing execution with the help of Timer is lighter and simpler than the traditional timing process, but it also has obvious shortcomings. When the service is shut down, all timing threads will be destroyed along with the main process. The prerequisite for all threads to be successfully executed is that the service must be stable and cannot be restarted. If you want to restart the service, you need to find a way to write the unfinished tasks to the disk (such as writing to the database), and then read the previously unfinished tasks and recreate the timing thread when starting the service.
Related recommendations:
Detailed explanation about reading and writing files in Python
The above is the detailed content of Python sample code for regularly modifying the database_python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.
