Home Backend Development Python Tutorial Python sample code for regularly modifying the database_python

Python sample code for regularly modifying the database_python

Apr 08, 2018 am 10:42 AM
python database Example

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()
Copy after login


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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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 and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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 vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

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: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

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's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

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 vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

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 vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

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.

See all articles