6th lesson: datetime Modules, operational databases, __name__, Redis, mock interfaces

Source: Internet
Author: User
Tags install redis

1. DateTime module
Import Datetimeprint (Datetime.datetime.today ())  # Current Time 2018-01-23 17:22:35.739667print (Datetime.datetime.now ()  # as in today 2018-01-23 17:22:35.739667print (Datetime.datetime.today (). Strftime ('%h:%m:%s '))  # Format a good time string in the specified format print (datetime.datetime.today () + Datetime.timedelta ( -3))  # three days before three days (3) 2018-01-20 17:25:37.470085print (Datetime.date.today ())  # Date of day 2018-01-23
2. Working with MySQL Database
Import Pymysqlimport config# 1. Connection mysql,ip port number user name password database # 2. Build Cursor # 3. Execute sql# 4. Gets the result # 5. Close Cursor # 6. Close Connection # CharSet must write UTF8, write utf-8 will error conn = Pymysql.connect (Host=config.host, Port=config.port, User=config.user, passwd= CONFIG.PASSWD,                       db=config.dbname, charset= ' utf8 ') cur = conn.cursor ()  # establishes a cursor, which gets the returned result as a tuple # cur = conn.cursor (cursor=pymysql.cursors.dictcursor)  # This way gets to the result that the dictionary type of sql = ' select * from Bt_stu limit 2; ' # sql = "INSERT into Bt_stu values (560, ' QQ ', 1, 18101000001, ' China ', 1);" Cur.execute (SQL)  # Execution Sqlconn.commit () res = Cur.fetchall ()  # Gets the result of the SQL statement execution, is a two-dimensional tuple # res1 = Cur.fetchone ()  # get only one result, it results in a one-dimensional tuple print (res) # print (res1) # # cur.scroll (0, mode= ' absolute ')  # move cursor, absolute path, move to front # cur.scroll (0, Mode= ' relative ')  # Move the cursor, relative to the current position cur.close () Conn.close ()
3. If __name__ = = ' __main__ ': # Usage
A.pyprint ("Outside:", __name__)  # Other file import this file, run the result is the current file name toolsif __name__ = ' __main__ ':  # When someone imports this file, this function does not execute,    print (' main: ', __name__)  # When running the current file, the result is __main__

  

b.py
# import a file in essence is to run this file over # import file if there is an if __name__ = = ' __main__ ', import this file from time to time do not execute this function imports a# run this file output is a
4. Redis Operations
1. Relational databases: such as MySQL Oracle SQL Server     
Non-relational database:
In the Key-value format
Memcahe # exists in memory
Redis # exists in memory
MongoDB # Data exists on disk
2. Redis Installation: Pip install Redis
3.
Import redis# Redis has only a password, no user name # String Type r = Redis. Redis (host= ' 211.149.***.** ', port=6379, password= ' ****** ', db=1) # port default 6379# r.set (' qxy_session ', ' 201801211506 ') # Set Data # Print (R.get (' qxy_session ')) # The data that Redis takes out is the bytes Type B ' 201801211506 ' # print (R.get (' qxy_session '). Decode ()) # So you need to use the Decode method to turn the string 201801211506# r.delete (' qxy_session ') # Delete a # R.setex (' Qxy ', ' hahaha ', 20) # can specify the expiration time of the key, in seconds # set G The ET delete Setex are all k-v# for string type R.set (' Qxy:test1 ', ' no Jobs ') r.set (' Qxy:test2 ', ' handed in the job ') print (R.keys ()) # gets all Keyprint (R.keys (' qxy* ')) # Keyprint (R.type (' Qxy:test1 ')) # starting with Txz # get the type of key # hash type R.hset (' qxy_sessions ', ' Q1 ', ' 1 ') # plug into Data r.hset (' qxy_sessions ', ' Q2 ', ' 2 ') r.hset (' qxy_sessions ', ' Q3 ', ' 3 ') print (R.hget (' qxy_sessions ', ' Q1 '). Decode ()) # Get a piece of data print (R.hgetall (' qxy_sessions ')) # gets all the types in the hash type All_data = {}for k,v in R.hgetall (' qxy_sessions '). Items (): K = K.decode () v = V.decode () all_data[k] = Vprint (all_data) # hash type no expiration time

Exercises

Import redis# migrating data from Redis db1 to DB8 r = Redis. Redis (host= ' 211.149.***.** ', port=6379, password= ' ****** ', db=1) r_new = Redis. Redis (host= ' 211.149.***.** ', port=6379, password= ' ****** ', db=8) for K in R.keys ("):    if R.type (R.keys ()) = = B ' String ':  # or with decode ()        v = r.get (k)        R_new.set (k, v)        print (V.decode ())    elif R.type (R.keys ()) = = B ' Hash ':        keys = R.hgetall (k)        for KK, VV in Keys.items ():            R_new.hset (k, KK, VV)
5. Development interface
    1. The usefulness of a mock (analog) interface

1) temporarily replace the third-party interface

2) Auxiliary testing: To replace the interface that is not well developed

    3) View data

2. Install the Flask module First: Pip Install flask

Import flaskfrom conf import configimport jsonfrom lib.tools import op_mysql# Import Tools # Tools.op_mysql () # Interface, background service Ser ver = flask. Flask (__name__) @server. Route ('/get_user ', methods=[' get ', ' post ') # This sentence means that this function becomes the interface Def get_all_user (): sql = ' Select    * from users; ' Response = Op_mysql (host=config. HOST, User=config. USER, Password=config. PASSWORD, Db=config. DBNAME, Port=config. PORT, charset= ' UTF8 ', sql=sql) res = json.dumps (response, Ensure_ascii=false, indent=4) retur N Res@server.route ('/add_user ', methods=[' post ') def add_users (): User = Flask.request.values.get (' user ') passwd = f Lask.request.values.get (' passwd ') print (user, passwd) if user and passwd:sql = "INSERT into users values ('%s ', '%s '); "% (user, passwd) op_mysql (host=config. HOST, User=config. USER, Password=config. PASSWORD, Db=config. DBNAME, Port=config. PORT, charset= ' UTF8 ', sql=sql) response = {' Code ': $, ' msg ': ' Operation succeeded '} Else:resPonse = {' Code ': 503, ' msq ': ' Required parameter not filled '} return Json.dumps (response, Ensure_ascii=false) # host= ' 0.0.0.0 ' for everyone in a LAN can visit  Add debug: Do not need to restart service Server.run (port=8888, host= ' 0.0.0.0 ', debug=true)

Access these two interfaces in postman

6th lesson: datetime Modules, operational databases, __name__, Redis, mock interfaces

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.