


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!

ThedifferencebetweenaforloopandawhileloopinPythonisthataforloopisusedwhenthenumberofiterationsisknowninadvance,whileawhileloopisusedwhenaconditionneedstobecheckedrepeatedlywithoutknowingthenumberofiterations.1)Forloopsareidealforiteratingoversequence

In Python, for loops are suitable for cases where the number of iterations is known, while loops are suitable for cases where the number of iterations is unknown and more control is required. 1) For loops are suitable for traversing sequences, such as lists, strings, etc., with concise and Pythonic code. 2) While loops are more appropriate when you need to control the loop according to conditions or wait for user input, but you need to pay attention to avoid infinite loops. 3) In terms of performance, the for loop is slightly faster, but the difference is usually not large. Choosing the right loop type can improve the efficiency and readability of your code.

In Python, lists can be merged through five methods: 1) Use operators, which are simple and intuitive, suitable for small lists; 2) Use extend() method to directly modify the original list, suitable for lists that need to be updated frequently; 3) Use list analytical formulas, concise and operational on elements; 4) Use itertools.chain() function to efficient memory and suitable for large data sets; 5) Use * operators and zip() function to be suitable for scenes where elements need to be paired. Each method has its specific uses and advantages and disadvantages, and the project requirements and performance should be taken into account when choosing.

Forloopsareusedwhenthenumberofiterationsisknown,whilewhileloopsareuseduntilaconditionismet.1)Forloopsareidealforsequenceslikelists,usingsyntaxlike'forfruitinfruits:print(fruit)'.2)Whileloopsaresuitableforunknowniterationcounts,e.g.,'whilecountdown>

ToconcatenatealistoflistsinPython,useextend,listcomprehensions,itertools.chain,orrecursivefunctions.1)Extendmethodisstraightforwardbutverbose.2)Listcomprehensionsareconciseandefficientforlargerdatasets.3)Itertools.chainismemory-efficientforlargedatas

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.


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

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!
