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 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)

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

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.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles