Setting Up Databases With Postgresql, Psequel, and Python
Setting Up Databases With Postgresql, Psequel, and Python
Setting Up Databases With Postgresql, Psequel, and Python
PostgreSQL, PSequel,
and Python
(image source: https://avataai.com/big-data-streaming-processing/)
As the demand for Data Scientists continues to increase, and is
being dubbed the the “sexiest job job of the 21st century” by
various outlets (including Harvard Business Review), questions
have been asked of what skills should aspiring data scientists
master on their way to their first data analyst job.
There is now a plethora of online courses to gain the skills needed
for a data scientist to be good at their job (excellent reviews of
online resources here and here). However, as I reviewed the
various courses myself , I noticed that a lot of focus is put on
exciting and flashy topics like Machine Learning and Deep
Learning without covering the basics of what is needed to gather
and store datasets needed for such analysis.
(Big) Data Science
Before we go into PostgreSQL, I suspect many of you have the
same question: why should I care about SQL?
Example of an ERD
(source: http://www.datanamic.com/dezign/erdiagramtool.html)
This is particularly important when dealing with the large datasets
found in Big Data applications. Such applications would have tens
of TBs in databases with several billion rows.
Data Scientist often start with SQL queries that would extract 1%
of data needed to a csv file, before moving to Python Pandas for
data analysis.
Enter PostgreSQL
There is a way to learn SQL without leaving the much loved
Python environment in which so much Machine Learning and
Deep Learning techniques are taught and used: PostgreSQL.
Once ready, click “Run Query”. The table will then be created in
the database. Don’t forget to click the “Refresh” icon (bottom
right) to see the table listed.
We are now ready to populate our columns with data. There are
many different ways to populate a table in a database. To enter
data manually, the INSERT will come in handy. For instance, to
enter the country Morocco with id number 1, and Australia with id
number 2, the SQL command is:
INSERT INTO country_list (id, name) VALUES (1, 'Morocco');
INSERT INTO country_list (id, name) VALUES (2, 'Australia');
After running the query and refreshing the tables, we get the
following table:
COPY country_list_csv(id,name)
FROM 'C:\{path}\{file_name}.csv' DELIMITER ',' CSV HEADER;
As you can see in the commands above, the table with column
names is specified after the COPY command. The columns must be
ordered in the same fashion as in the CSV file. The CSV file path is
specified after the FROMkeyword. The CSVDELIMITER must also be
specified.
If the CSV file contains a header line with column names, it is
indicated with the HEADER keyword so that PostgreSQL ignores the
first line when importing the data from the CSV file.
Common SQL commands
The key to SQL is understanding statements. A few statements
include:
SELECT is where you tell the query what columns you want back.
FROM is where you tell the query what table you are querying
from. Notice the columns need to exist in this table. For example,
let’s say we have a table of orders with several columns but we are
only interested in a subset of three:
import psycopg2
conn = psycopg2.connect(database="sample_db", user = "postgres",
password = "pass123", host = "127.0.0.1", port = "5432")
Conclusion
You now have a working PostgreSQL database server ready for you
to populate and play with. It’s powerful, flexible, free and is used
by numerous applications.
Menjadi Developer Web dengan
Python dan Flask IV: Database
Database di Flask
Mungkin pembaca sudah tahu sebelumnya bahwa Flask tidak memiliki fitur
database bawaan. Database merupakan salah satu area dimana kita diberikan
kebebasan untuk memilih database apa yang cocok dengan aplikasi kita
daripada dipaksa untuk menggunakan satu solusi saja.
Ada banyak pilihan database untuk Python yang bagus, kebanyaka mereka
memiliki ekstensi Flask sehingga membuat proses integrasi ke aplikasi menjadi
lebih baik. Database dapat dibagi menjadi dua grup yaitu grup yang mengikuti
model relasi dan grup yang tidak mengikuti model relasi. Grup yang dikedua
sering disebut NoSQL yang mengindikasikan bahwa mereka tidak
mengimplementasi SQL. Meski ada banyak produk database yang bagus di
kedua grup tersebut, penulis merasa bahwa database relasiional lebih cocok
untuk aplikasi yang memiliki struktur data seperti daftar user, blog, post, dll.
sementara NoSQL cocok untuk data yang kurang terstruktur. Aplikasi yang
akan kita buat dapat diimplementasi menggunakan database manapun, namun
karena alasan yang sebelumnya sudah penulis kemukakan, maka kita hanya
akan menggunakan database relasional.
Di artikel sebelumnya penulis sudah mengenalkan ekstensi Flask. Di bab ini kita
akan kembai menggunakan dua ekstensi yaitu Flask-SQLAlchemy, ekstensi
Flask untuk menggunakan paket SQLAlchemy yang sudah dibungkus
sedemikian rupa sehingga lebih ramah terhadap kode Flask. SQLAlchemy
adalah sebuah Object Relational Mapper atau ORM. ORM memungkinkan
aplikasi untuk menggunakan database dengan data high-level seperti kelas,
objek dan method daripada menggunakan tabel dan kode SQL secara langsung.
Tugas ORM adalah menerjemahkan operasi high-level menjadi perintah
database.
Hal yang menarik tentang SQLAlchemy adalah bahwa ia bukan ORM hanya
untuk satu sistem database. SQLAlchemy mendukung banyak sistem database
diantaranya MySQL, PostgreSQL dan SQLite. Fitur ini sangat berguna karena
kita bisa memakai sistem SQLite sederhana di lingkungan development lalu
menggunakan sistem yang lebih terjamin untuk production menggunakan
MySQL atau PostgreSQL tanpa mengubah aplikasi.
Ekstensi kedua yang akan kita pakai di bab ini adalah Flask-Migrate. Ekstensi
ini merupakan pembungkus Flask untuk Alembic, sebuah database migration
framework-nya SQLAlchemy. Bekerja dengan database migrations akan
menambah pekerjaan dalam menyiapkan database, namun tambahan kerjaan ini
merupakan harga yang murah dibandingkan keuntungan yang akan kita
dapatkan di masa mendatang.
Proses pemasangan Flask-Migrate mirip dengan proses yang sudah kita lakukan
sebelumnya:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
# ...
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
SQLALCHEMY_TRACK_MODIFICATIONS = False
Konfigurasi SQLALCHEMY_TRACK_MODIFICATIONS diatur nilainya
menjadi Falseuntuk mendisable fitur Flask-SQLAlchemy yang tidak
dibutuhkan (fitur untuk memberitahu aplikasi tiap kali terjadi perubahan di
database)
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
Ada tiga perubahan yang kita buat. Pertama, kita membuat objek db yang
merepresentasikan database. Lalu kita juga menambah objek lain sebagai
migration enginenya. Semoga pembaca sudah mulai bisa melihat pola
penggunaan ekstensi Flask. Sebagian besar ekstensi diinisialisasikan seperti dua
objek tersebut. Terakhir kita mengimpor modul baru bernama model di bagian
bawah. Modul ini akan mendefinisikan struktur database.
Database Models
Data yang akan disimpan didalam database diwakilkan oleh kumpulan kelas,
biasanya disebut dengan database model. Lapiran ORM didalam SQLAlchem
akan menerjemahkan objek dari model menjadi tabel-tabel SQL yang
diperlukan.
Mari kita mulai membuat model yang mewakilkan user. Dengan
memakai WWW SQL Designer tool, kita dapat membuat diagram seperti pada
gambar:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
>>> u
<User susan>
Generating
/home/miguel/microblog/migrations/versions/e517276bb1c2_users_table.py ... done
Teks yang dihasilkan dari perintah di atas mungkin bisa menggambarkan apa
yang ditambahkan olehh Alembic ke sebuah migration. Dua baris pertama
biasanya bisa diabaikan. Alembic lalu mengatakan bahwa ia menemukan sebuah
tabel user dan dua indeks. Ia lalu memberitahu dimana ia membuat skrip
migrationnya. Kode e517276bb1c2 dibuat secara otomatis dan akan selalu
berbeda untuk tiap orang. Opsi -m pada perintah di atas tidak wajib dipakai, ia
hanya menambah deskripsi singkat disebelah baris migration.
Skrip migration yang dibuat juga menjadi bagian dari aplikasi sehingga perlu
ditambahkan juga ke source control. Pembaca bisa melihat isi skrip tersebut jika
penasaran dengan isinya. Pembaca akan melihat dua fungsi
bernama upgrade()dan downgrade(). Fungsi upgrade() akan
mengaplikasikan migration dan downgrade() akan menghapusnya (kebalikan).
Kedua fungsi ini memungkinkan Alembic untuk mengatur database untuk
kembali ke schema tertentu dari versi migration sebelum-sebelumnya dengan
fungsi downgrade.
Setelah sudah siap untuk merilis versi baru aplikasi ke server production, yang
perlu kita lakukan selanjutnya adalah mengirim versi aplikasi yang baru
(termasuk skrip migration-nya) lalu menjalankan perintah flask db upgrade.
Alembic akan mendeteksi bahwa database di production belum menggunakan
schema terbaru sehingga akan menjalankan skrip-skrip baru setelah rilis
sebelumnya.
Relasi Database
Database relasional dapat menyimpan relasi antar data dengan sangat baik.
Bayangkan kasus dimana seorang user menulis sebuah artikel blog. User
tersebut akan memiliki data di tabel users dan artikel akan disimpan di
tabel posts. Cara paling efektif untuk menyimpan data siapa yang menulis
artikel tertentu ialah dengan menghubungkan dua tabel tersebut.
Setelah hubungan antara seorang user dan sebuah artikel terhubung, database
dapat menjawab permintaan data yang diperlukan. Misalnya ada sebuah artikel
dimana kita ingin mengetahui siapa user yang menulisnya, atau kita memiliki
data seorang user dan ingin mencari semua artikel yang ditulisnya. Flask-
SQLAlchemy dapat membantu kueri-kueri seperti ini.
Mari kita perbarui dataabse untuk menyimpan artikel (blog posts) untuk melihat
bagaimana sebuah relasi terjadi. Berikut ini schema untuk tabel posts yang
baru:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
def __repr__(self):
Generating
/home/miguel/microblog/migrations/versions/780739b227a7_posts_table.py ... done
Play Time
Penulis sudah menyusahkan pembaca dalam proses panjang pembuatan
database, namun penulis belum menunjukkan bagaimana kode-kode kita tadi
bekerja. Sekarang mari kita bermain dengan database menggunakan interpreter
Python untuk lebih mengenalnya. Maka, sekarang buka Python dengan
memanggil perintah python. Pastikan virtual environment sudah aktif sebelum
memanggilnya.
>>> db.session.add(u)
>>> db.session.commit()
Perubahan ke database dilakukan dalam konteks session yang dapat diliat
di db.session. Perubahan-perubahan yang dilakukan diakumulasi disebuah
session dan setelah semua perubahan didaftarkan ke sana kita bisa mamanggil
satu perintah db.session.commit() yang akan mengaplikasikan perubahan-
perubahan tersebut. Jika saat bekerja dengan session terjadi
error, db.session.rollback() akan dipanggil secara otomatis dan
membatalkan semua perubahan di session tersebut. Yang perlu diingat adalah
perubahan-perubahan hanya akan ditulis ke database hanya
jika db.session.commit() di panggil.
>>> db.session.add(u)
>>> db.session.commit()
>>> users
...
1 john
2 susan
Berikut ini cara lain melakukan kueri. Jika kita sudah mengetahui nilai id salah
satu user, kita bisa mengambil objek user tersebut dengan perintah:
>>> u = User.query.get(1)
>>> u
<User john>
>>> u = User.query.get(1)
>>> db.session.add(p)
>>> db.session.commit()
Untuk menyelesaikan bagian ini, mari kita lihat beberapa kueri lain:
>>> u = User.query.get(1)
>>> u
<User john>
>>> posts
>>> u
<User susan>
>>> u.posts.all()
[]
...
>>> User.query.order_by(User.username.desc()).all()
Mari kita harus seluruh data yang kita buat di atas sehingga database menjadi
bersih dan siap digunakan di bab berikutnya:
... db.session.delete(u)
...
... db.session.delete(p)
...
>>> db.session.commit()
Shell Context
Masih ingat apa yang kita lakukan setelah memulai interpreter Python di bagian
sebelumnya? Hal pertama yang kita lakukan adalah mengimpor modul dan keals
yang diperlukan:
Saat membuat aplikasi Flask, kita mungkin perlu menguji beberapa hal melalui
shell Python sehingga mengulang-ulang impor di atas mungkin dapat
membosankan. Perintah flask shell adalah opsi lain dari perintah flask yang
akan memulai interpreter Python dan mengimpor seluruh kelas yang
berhubungan dengan aplikasi Flask kita. Perhatikan contoh di bawah:
(venv) $ python
>>> app
>>>
(venv) $ flask shell
>>> app
<Flask 'app'>
@app.shell_context_processor
def make_shell_context():
>>> db
<SQLAlchemy engine=sqlite:////Users/migu7781/Documents/dev/flask/microblog2/app.db>
>>> User
<class 'app.models.User'>
>>> Post
<class 'app.models.Post'>
http://www.postgresqltutorial.com/postgresql-python/
How do I integrate a payment gateway in a website
developed in PHP?
Ad by JetBrains
Great code assistance, smart debugger, safe refactorings, all major PHP frameworks support.
Try for free!
Download at jetbrains.com
10 Answers
If you want to integrate Paypal Payment gateway in your PHP website, take a look at some
help on Paypal integration in PHP Website: How to integrate payment system with PayPal
in php & Mysql - iGreenTech Services
3.7k Views
Related QuestionsMore Answers Below
PayPal is the most popular payment gateway to send and receive payment worldwide.
PayPal payment gateway is the easiest option for the web developer to implement payment
system on the website.
Once the user clicks on the Buy Now/Payment button, they will be redirected to the PayPal
where the payment will complete.
After payment completion, the user will be redirected back to the website and the
transaction details to be shown to the user.
Also, the transaction information would be stored in the MySQL database.
Sandbox
Live.
PayPal Sandbox allows developers to do their test transaction before the project go live.
Live environment is used after project live. Once PayPal payment process is working fine on
Sandbox environment, you can set PayPal to Live environment.
Database Tables Creation
Payment Success (success.php)
Once the PayPal payment is successful, the buyer is redirected to this page. The transaction
information is received using $_GET method and inserts payment data into the database.
If the buyer wishes to cancel payment at the PayPal payment page, the buyer is redirected to
this page.
1. Your PayPal transaction has been canceled.
IPN
To make the PayPal Standard Payment more secure, Instant Payment Notification (IPN)
should be used to validate the transaction.
Enable IPN
To Use this feature, IPN must be enabled in PayPal account.
Please go to the below link.
Identifying Your IPN Listener to PayPal
Validate Transaction
Once IPN is enabled PayPal will send the transaction data to the Notify URL
(http://walkeprashant.in/ipn.php). Place the following code in ipn.php file to validate and
insert payment information into the database
1. <php
2. //Database credentials
3. $dbHost = 'localhost';
4. $dbUsername = 'root';
5. $dbPassword = '';
6. $dbName = 'walkeprashantdb';
7.
8. //Connect with the database
9. $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
10.
11. //Display error if failed to connect
12. if ($db->connect_errno) {
13. printf("Connect failed: %s\n", $db->connect_error);
14. exit();
15. }
16. $raw_post_data = file_get_contents('php://input');
17. $raw_post_array = explode('&', $raw_post_data);
18. $myPost = array();
19. foreach ($raw_post_array as $keyval) {
20. $keyval = explode ('=', $keyval);
21. if (count($keyval) == 2)
22. $myPost[$keyval[0]] = urldecode($keyval[1]);
23. }
24.
25. // Read the post from PayPal system and add 'cmd'
26. $req = 'cmd=_notify-validate';
27. if(function_exists('get_magic_quotes_gpc')) {
28. $get_magic_quotes_exists = true;
29. }
30. foreach ($myPost as $key => $value) {
31. if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1)
{
32. $value = urlencode(stripslashes($value));
33. } else {
34. $value = urlencode($value);
35. }
36. $req .= "&$key=$value";
37. }
38.
39. /*
40. * Post IPN data back to PayPal to validate the IPN data is genuine
41. * Without this step anyone can fake IPN data
42. */
43. $paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
44. $ch = curl_init($paypalURL);
45. if ($ch == FALSE) {
46. return FALSE;
47. }
48. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
49. curl_setopt($ch, CURLOPT_POST, 1);
50. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
51. curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
52. curl_setopt($ch, CURLOPT_SSLVERSION, 6);
53. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
54. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
55. curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
56.
57. // Set TCP timeout to 30 seconds
58. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
59. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-
Agent: company-name'));
60. $res = curl_exec($ch);
61.
62. /*
63. * Inspect IPN validation result and act accordingly
64. * Split response headers and payload, a better way for strcmp
65. */
66. $tokens = explode("\r\n\r\n", trim($res));
67. $res = trim(end($tokens));
68. if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0)
{
69.
70. //Payment data
71. $item_number = $_POST['item_number'];
72. $txn_id = $_POST['txn_id'];
73. $payment_gross = $_POST['mc_gross'];
74. $currency_code = $_POST['mc_currency'];
75. $payment_status = $_POST['payment_status'];
76.
77. //Check if payment data exists with the same TXN ID.
78. $prevPayment = $db->query("SELECT payment_id FROM payments WHERE
txn_id = '".$txn_id."'");
79. if($prevPayment->num_rows > 0){
80. exit();
81. }else{
82. //Insert tansaction data into the database
83. $insert = $db->query("INSERT INTO
payments(item_number,txn_id,payment_gross,currency_code,payment_status)
VALUES('".$item_number."','".$txn_id."','".$payment_gross."','".
$currency_code."','".$payment_status."')");
84. }
85.
86. }
Make PayPal Payment Gateway Live
When your application payment flow testing is completed, you need to modify two files to
make PayPal payment gateway live.
979 Views
Promoted by DigitalOcean
Save up to 25% on your CI, data analysis and batch processing nodes. Try free for 60 days.
Hi There,
Each and every payment Gateway provider provides sets of API with documentation to
integrate in multiple language. To be more specific you need to be sure which payment
gateway you will be using.
For example, one my favorite payment gateway is Razorpay · Payment Gateway Solution for
India .
Now if you want to use this payment gateway you will find complete documentation
at Getting Started with Razorpay · Razorpay .
Before integrating you need to register and generate set you access ids. Once you are done
you can use PHP: cURL - Manual to make the calls to their APIs.
If you have any other doubts do reach me again.
1.6k Views
Promoted by MongoDB
Automated MongoDB service built for the most sensitive workloads at any scale. Get started
free.
While I was working at CanDeotech for approx 12 years, I used to get a lot of website
projects. And almost 7 out of 10 was to add a PG into them. We used to work mainly on
LAMP stack. Those were mostly overseas projects and PG = Paypal was the common ask
point.
So we had a script ready for that which we used to simply integrate. Now there are many
API’s & SDK’s available to do so for PHP. I am talking about 2004–2013.
Post 2013, we started working on Indian websites too. And the best thing which I later
found was JUSPAY.
JUSPAY is a payment wrapper. So if you will integrate one JUSPAY wrapper into a website,
you wont have to again and again work on script integration or wont have to spend money
on development hours.
Register on JusPay.
Integrate the JUSPAY console for once. Get through with testing & results.
Later whenever & how many PG’s available in India you signup with, you can simply let
those PG companies know, that you have JUSPAY as a wrapper. They will provide you with
JUSPAY clearance at their backend & their Credentials.
You dont need to be a developer to then add any pg, whether its PAYU, RAZORPAY, EBS,
CCAVENUE, etc.
Once you get your application approved with the PG company, you will receive the
credentials in your Registered Email address.
Login to your JUSPAY account, Select your PG & add those credentials, like you fill a form,
and your PG is live!
Adding more awesomeness is, if you have 3 PG’s, JUSPAY gives your Priority LOGIC setup,
which has basic & advanced setting options. And you can use all 3 PG’s at your PHP website.
I will advise you to surely try JUSPAY, if you are a developer. It will save you lot of time &
money!
PS: I dont work for JUSPAY. Just that I understand the PAIN the developer goes through
everytime while integrating PAYMENT Gateways.
Thanks.
Saurabh - Working at Pay with Credit Card anytime, anywhere & anyone | PAYDECK
1.4k Views
To integrate a Payment Gateway into your website, you must always hire a professional and
experienced company to ensure security and reliability, facilitating safe online transactions.
Since a Payment Gateway is the most important aspect of any online business, a
professionally qualified company seamlessly integrates any Payment Gateway of your
choice, making shopping carts friendly, secure and reliable, to business owners and their
customers.
There's a company that I know of which is helping Online Businesses with online
transactions. The company is Enuke Software Pvt. Ltd. To knw about their work, you
can visit Payment Gateway Integration
1.4k Views
Abhishek Banerjee, Software Engineer
Answered Feb 12 2015 · Author has 53 answers and 51.1k answer views
Aleksandra Seremina
Answered May 16, 2016 · Author has 157 answers and 155.4k answer views
The simplest way is to use a Paypal button adding it to the appropriate place at your
website. However, there is another more complex but more efficient way. You can create
your own HTML-form that contains all the necessary data for making payments.
There are ready-made modules for a majority of CMS and they allow integrating Paypal
payment gateway with an e-commerce site. For example, a module for Drupal 7 and his
module Commerce: Commerce PayPal | Drupal.org
If you interested in some specific details and tips on Paypal integration, take a look
here: http://cases.azoft.com/integrate...
1.6k Views · View Upvoters
You can contact iPistis Technologies pvt. ltd. , this company is providing integration
services for almost all payment gateway in PHP
436 Views
Each payment gateway has its own api which asks you to send some basic info to a url like
Initial page
Order number amount
Failure page
Success page