2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ajax + Python + PostgreSQL のサンプル

Posted at

はじめに

  • データベースからデータを取得し、動的なWebページを作成するサンプル

サンプル

  • index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>

//var data = 10;
//var data_list=['hoge','geho];

function get_data(data, data_list){
  var request = {
    data1 : data,
    data2 : data_list
  };
  $.ajax({
    url: 'get_data.py',
    type: 'POST',
    data: JSON.stringify(request)
  })
  .done(function(data){
    result = JSON.parse(data);
    for (i=0;i<result.length;i++){
      console.log(result[i][0]);
    }
  })
  .fail(function(){
    console.log('failed');
  });
};
  • get_data.py
import sys
import json
import psycopg2

# connect postgreSQL
users = 'postgres'  
dbnames = 'postgres'
passwords = '*******'

conn = psycopg2.connect(" user=" + users +" dbname=" + dbnames +" password=" + passwords)
cur = conn.cursor() 

# index.htmlから飛ばしたデータを取得
recieve = sys.stdin.read()
params = json.loads(recieve)

data = params["data1"]
data_list = params["data2"]

# SQL文を作成し実行
sql = 'select data from dataTbale where (AAA = data) and ((BBB = data_list[0]) or (BBB = data_list[1]))'
cur.execute(sql)
results = cur.fetchall()
conn.commit()

# 後片付け
cur.close()
conn.close()

# index.html側に通知
print('Content-type: text/html\n')
print(json.dumps(results))

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?