Facets | Use Python to connect to a database, insert and query data--link

Source: Internet
Author: User
Tags curl docker run

1, connect two Docker

First, you need to build the environment:

Create the MARIADB database below Alpine:

http://blog.csdn.net/freewebsys/article/details/53540615

User name password is root.

Then create the HTTP Python environment:

http://blog.csdn.net/freewebsys/article/details/53509676

Next, do a simple data query and insert operation.

2,python Code:

main.py

#!/usr/bin/python#-*-Coding:utf-8-*-From flaskImport FlaskImport MySQLdb app = Flask (__name__) Mysql_host ="MySQL" Mysql_user ="Root" mysql_pwd ="Root" Mysql_db_name ="Demo""" "CREATE DATABASE ' demo ' DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci; CREATE TABLE ' demo '. ' User_info ' (' id ' bigint) NOT null auto_increment, ' name ' varchar ($) DEFAULT NULL, PRIMARY KEY ( ' id ') engine=innodb DEFAULT Charset=utf8; """Defquery_db(SQL): db = MySQLdb.connect (Mysql_host, Mysql_user, mysql_pwd, mysql_db_name) cur = db.cursor ()Try:cur.execute (sql) result = Cur.fetchall ()Except:print ("Error:sql:" + sql) Cur.close () Db.close ()return resultDefupdate_db(SQL): print (SQL) db = MySQLdb.connect (Mysql_host, Mysql_user, mysql_pwd, mysql_db_name) cur = db.cursor ()Try:cur.execute (SQL)Except:print ("Error:sql:" + sql) Db.commit () Cur.close () Db.close ()@app. Route ("/list")Def list ():    results = query_db ( "Select Id,name from ' demo '. ' User_info '")     out = "results:\n"      for result  in results:        id = result[ 0]        name = result[ 1]        out +=  "ID:"  + str (ID) +  ", Name:"  + name + "\ n"      return out @ App.route ("/add") def  add ():    sql =  "Insert ignore into" Demo '. ' User_info ' (' name ') VALUES (' Zhangsan ') '     update_db (SQL)     return  "OK" if __name__ ==  "__main__":    app.run (host= ' 0.0.0.0 ', port= ()

The code is not much different from the previous HTTP, but it only adds query and insert operations to the database.

Altogether there are two URLs, a list, query all data, an add, write dead increase.

3. Create a database table

MySQL needs to create the following database and table:


CREATE DATABASE ' demo ' DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci; CREATE TABLE' demo '. ' User_info ' (' id ' bigint () not NULL auto_increment,' name ' varchar Default NULL,PRIMARY KEY (' id ')) engine=innodb default Charset=utf8;

This User_info table has a total of two fields, an ID increment, and a name string.

Of course, this database is not local and is another Docker container.

HTTP is above a container.

4, use link to link up

The data creation name is called MARIADB.

Run HTTP.

Docker run -D -P: --name py-http -link mariadb:mysql demo/py-http: 1.0

Pay special attention to the –link container name: Nickname, and then for the Py-http container, MySQL is the nickname.

You can look directly at the EVN environment:

# docker Exec-it Py-http

bashbash-4.3# env

hostname=db7f7aba7c2f

Mysql_env_mysql_root_password=root

Mysql_env_mariadb_version=10.1.19+maria-1~jessie

mysql_env_gosu_version=1.7

mysql_port_3306_tcp_port=3306

mysql_env_mariadb_major=10.1

mysql_port_3306_tcp=tcp://172.17.0.2:3306

Path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

pwd=/

Tz=asia/shanghai

Shlvl=1Home=/root

Mysql_name=/py-http/mysql

Mysql_port_3306_tcp_proto=tcp

mysql_port_3306_tcp_addr=172.17.0.2

mysql_port=tcp://172.17.0.2:3306

_=/usr/bin/env

As you can see, the environment variables of the MARIADB container have been introduced directly under the Py-http container.

and view hosts:

# cat/etc/hosts

127.0.0.1 localhost::1 localhost ip6-localhost ip6-loopback

Fe00::0 ip6-localnet

FF00::0 Ip6-mcastprefix

FF02::1 Ip6-allnodes

FF02::2 ip6-allrouters

172.17.0.2 MySQL 48bd5fbf3ddc mariadb

172.17.0.3 db7f7aba7c2f

You can see the host with the MySQL variable.

External access: Indicates that the test was successful. The database can be inserted into the query.

# Curl Http://127.0.0.1:5000/add

Ok[[email protected] http]# curl Http://127.0.0.1:5000/list

Results

ID:1,Name:zhangsan

ID:2,Name:zhangsan

4, summary

Docker design is good, each container is independent, but can also be connected together.

This makes up a micro-service cluster. Separate the code from the environment with environment variables.

Ensure the consistency of test environment, development environment and online environment.

Greatly facilitates the development of operations, the link command is also very good.

New Wisdom Cloud Official website www.enncloud.cn

Facets | Use Python to connect to a database, insert and query data--link

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.