Here is how to log in as the postgres user in Linux distributions like Arch Linux, Debian, Ubuntu, or Kali Linux. Accessing the postgres account is necessary to configure and manage your PostgreSQL server.
First, switch from your standard user account to the root user:
sudo su
Next, switch from the root account to the postgres user:
sudo su postgres
Below is the command to switch directly to the postgres user using a single command:
sudo -i -u postgres
Below is the command to view all users in a PostgreSQL server:
\du
Below is the command to view all available databases on a PostgreSQL server:
\l
Below is a SQL command for a PostgreSQL server that creates a new user named 'steven' with the password 'rahasia' and grants them permission to create databases:
CREATE USER steven WITH PASSWORD 'rahasia' CREATEDB;
This is the source code for creating a RESTful API server that will send data in JSON format over the network.
from flask import Flask, render_template, request, url_for, redirect, jsonify
from jinja2 import Template, Environment, FileSystemLoader
import csv
import sys
import json
aplikasi = Flask(__name__)
@aplikasi.route('/data')
# ini adalah source code untuk membuat server RESTFUL API yang akan mengirimkan data dalam bentuk JSON di jaringan
def halaman1():
data = {}
with open('/home/steven/proyekFlask/latihan15/templates/file2.csv','r') as file:
pembacaCSV = csv.DictReader(file)
for rows in pembacaCSV:
key = rows['nomer']
data[key] = rows
return jsonify(data)
if __name__ == '__main__':
aplikasi.run(host="0.0.0.0",port=8543,debug=True)
The following source code is used to consume JSON data sent by the RESTful API server. The RESTful API server is also created using the Python language.
from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS
import requests
aplikasi = Flask(__name__)
CORS(aplikasi)
# ini adalah program komputer untuk mengkonsumsi data JSON yang di kirimkan oleh server lain
@aplikasi.route('/', methods=['GET'])
def tampilData():
r = requests.get('http://1.1.3.4:8543/data')
return r.json()
if __name__ == '__main__':
aplikasi.run(host="0.0.0.0",port=8544,debug=True)
Next, we will learn everything about flask_restful. So that we can learn various things related to RESTful API.
We will try to build data delivery over the network using a RESTful API. In building the server and backend RESTFUL API, we use the Python programming language. We will use JavaScript to build the UI. JavaScript will also be used to consume JSON data sent through the RESTFUL API. JavaScript will be used to build AJAX technology.
import json
from flask import Flask
import mariadb
import sys
aplikasi = Flask(__name__)
@aplikasi.route('/')
# di bawah ini adalah source code untuk mengirimkan data dalam bentuk JSON ke jaringan dan ditampilkan di browser
def restApi1():
return json.dumps({'nama':'alesandro','e-mail':'alesandro@toto.com'})
if __name__ == '__main__':
aplikasi.run(host="0.0.0.0",port=8543,debug=True)
The following is the source code for reading a text file. The results of the reading will then be displayed on the web page. Alternatively, the results of the reading can be sent using a RESTful API. Once the reading results are converted to JSON, they will be displayed on the web page using AJAX.
This is the source code for the data input page. There is also a button to display a table containing the data stored in the MariaDB table. There is also a button to return to the Menu page.
from flask import Flask, request, url_for, redirect, render_template
from jinja2 import Template, Environment, FileSystemLoader
import mariadb
import sys
aplikasi = Flask(__name__)
@aplikasi.route('/')
def halaman1():
return render_template('halaman1.html')
@aplikasi.route('/halaman2', methods=['GET','POST'])
def halaman2():
if request.method == 'POST':
# lakukan sesuatu ketika form di kumpulkan
# dialihkan untuk mengakhiri penanganan POST
# pengalihan bisa ke route yang sama atau ke sesuatu yang lain
return redirect(url_for('halaman1'))
# tampilkan form nya, form nya tidak di kumpulkan
return render_template('halaman2.html')
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0',port=8543,debug=True)
dataRoti = {'merekRoti':'Bondy','bulanPembuatan':'Februari','lokasiToko':'Gunung Sari'}
del dataRoti['bulanPembuatan']
print(dataRoti)
This is a source code that almost successfully displays data from the database into a table format.
This is the source code for the Python section.
import mariadb
import sys
from jinja2 import Template, Environment, FileSystemLoader
from flask import Flask, render_template, request
aplikasi = Flask(__name__)
@aplikasi.route('/')
def tampilkanData():
koneksi = mariadb.connect(user="steven",password="kucing",host="1.1.3.7",port=3306,database="saham")
kursor = koneksi.cursor(dictionary=True)
kursor.execute("SELECT idnama1,namaawal1,namaakhir1 FROM nama1")
hasil = kursor.fetchall()
koneksi.commit()
koneksi.close()
return render_template("halaman6.html",hasil=hasil)
if __name__ == '__main__':
aplikasi.run(host="0.0.0.0", port=8543, debug=True)
This is the source code for the HTML section.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Tampilkan Tabel</h1>
<table>
{% for hasil_item in hasil %}
{% for key, value in hasil_item.items() %}
<tr>
<th>{{ key }}</th>
</tr>
<tr>
<td>{{ value }}</td>
</tr>
{% endfor %}
{% endfor %}
</table>
</body>
</html>
This is the working source code to display the contents of a dictionary from the results of a database query. The data is displayed on an HTML page. This is an example of source code that uses HTML and Python.
The following are variations of HTML source code that will display different data results.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% for hasil2 in hasil1 %}
{% for key, value in hasil2.items() %}
{{ value }}
{% endfor %}
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% for hasil2 in hasil1 %}
{{ hasil2.keys() }}
{% endfor %}
</body>
</html>
This is the source code that successfully displays data in an HTML table correctly.
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<table>
<!----- Ini adalah source code untuk membuat header table ----->
{% if hasil1 %}
<tr>
{% for key in hasil1[0] %}
<th> {{ key }} </th>
{% endfor %}
</tr>
{% endif %}
<!--- Ini adalah source code untuk membuat isi tabel -->
{% for isitabel in hasil1 %}
<tr>
{% for value in isitabel.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</BODY>
</HTML>
This is a combination of querying the correct database and displaying the correct table (using CSS).
Python Code :
from flask import Flask, render_template, request
from jinja2 import Template, Environment, FileSystemLoader
import mariadb
import sys
aplikasi = Flask(__name__)
@aplikasi.route('/')
def tabelData():
koneksi = mariadb.connect(user="steven",password="kucing",host="1.1.3.7",port=3306,database="saham")
kursor = koneksi.cursor(dictionary=True)
kursor.execute("SELECT idnama1,namaawal1,namaakhir1 FROM nama1")
hasil = kursor.fetchall()
return render_template("halaman11.html",hasil1=hasil)
if __name__ == '__main__':
aplikasi.run(host="0.0.0.0", port=8543, debug=True)
HTML Code :
<!DOCTYPE html>
<html>
<head>
<style>
#dataNama {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#dataNama td, #dataNama th {
border: 1px solid #ddd;
padding: 8px;
}
#dataNama tr:nth-child(even){background-color: #f2f2f2;}
#dataNama tr:hover {background-color: #dataNama}
#dataNama th{
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #04AA6D;
color: white;
}
</style>
</head>
<body>
<table id="dataNama">
<!------- Ini adalah source code untuk membuat header table -------->
{% if hasil1 %}
<tr>
{% for key in hasil1[0] %}
<th> {{ key }} </th>
{% endfor %}
</tr>
{% endif %}
<!--- ini adalah source code untuk membuat isi tabel -->
{% for isitabel in hasil1 %}
<tr>
{% for value in isitabel.values() %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
Next, we will try to be able to create a table using this looping function.
This source code successfully displays data based on the looping results, but the data is still in the form of a list, not data that can be separated by rows and columns.
We will use the Dictionary concept to collect data from Mariadb. The data is the result of a query process from Mariadb. The Dictionary will be tried to be used to build a table on an HTML page.
Here are the steps on how to share internet from a laptop or PC using a USB WiFi Dongle. This will allow other devices to connect to the internet as well.
netsh wlan set hostednetwork mode=allow ssid=nasipecel key=makan1234 keyusage=temporary
netsh wlan start hostednetwork
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=disallow
netsh wlan stop hostednetwork
netsh wlan show settings
netsh wlan show profiles
netsh wlan delete profile name="swisscom"
netsh wlan delete profile name=* i=*
netsh wlan show drivers
https://stackoverflow.com/questions/18182084/cant-start-hostednetwork
https://support.airserver.com/support/solutions/articles/43000532725-how-can-i-enable-the-wireless-autoconfig-service-the-wireless-autoconfig-service-wlansvc-is-not-
https://youtu.be/2pvK-6321ig?si=tKonB-Tn-LIvcTTX
In this example, I am trying to query a MariaDB database. Then I am trying to display the results on a web page. However, for the first step, I will try to display the query results to the terminal. The following is the source code for printing database query results to the terminal:
import mariadb
import sys
koneksi = mariadb.connect(user="steven",password="kucing",host="1.1.3.6",port=3306,database="saham")
kursor = koneksi.cursor(dictionary=True)
kursor.execute("SELECT idnama1,namaawal1,namaakhir1 FROM nama1")
hasil = kursor.fetchall()
print(hasil[0])
The following source code successfully prints the query results from the MariaDB database to the terminal.
import mariadb
import sys
koneksi = mariadb.connect(user="steven",password="kucing",host="1.1.3.7",port=3306,database="saham")
kursor = koneksi.cursor(dictionary=True)
kursor.execute("SELECT idnama1,namaawal1,namaakhir1 FROM nama1")
hasil = kursor.fetchall()
print(hasil[1])
There will be a change in the language used on this blog, from Indonesian to a language other than Indonesian. In this blog, I will write about various things.
I have successfully compressed the size of a .jpeg photo file using the following software:
And in one article, I will try to achieve a target of 800 words or more. What I have learned in the past two days is about the applications Snackvideo and Bigo Live. The applications SnackVideo and Bigo seem to be more lenient than TikTok in terms of regulations. As a result, there are not many violations in both of these applications. Some users who perform live streaming on Bigo have moved their live streaming activities to the Line application. Perhaps this is because the rules on the Line application are more lenient than on Bigo. This is a rule related to the issue of nudity. In the Bigo app, in some live rooms, there are live room administrators who will remove viewers who only watch without giving any gifts to the host of the live room.
Today I have successfully changed the address of my blog to .web.id. I have also successfully connected it to AdSense. I am always learning how to make the links from my blog to be on various websites. In the afternoon, I studied about writing programming code using the Python programming language. The Python programming code was run in the Docker application. I have also successfully set up Google Analytics on this blog. I have already submitted this blog to Bing Webmaster and Yandex Webmaster, so this blog is also indexed in both of those search engines.
Building Docker Image
Here is the command to build a Docker image. Type the following command in the terminal of the host computer that has Docker :
Here is the command to find out who the user is in the specified Docker image:
sudo docker run --entrypoint "" python-mariadb1 whoami
The following command will remove a Docker image that has already been built :
sudo docker image rm <nama-repository>
The following command will list all containers that have been created :
sudo docker ps -a
Instructions for deleting a container :
sudo docker container rm (ID Container)
Example :
sudo docker container rm 9c9b1210e0c0
Instructions for running a Docker image on a Lokinet network :
sudo docker run -p 0.0.0.0:8543:8543 python-flask1
command to stop a running container :
sudo docker container stop (ID Container)
Example :
sudo docker container stop b4d3e8d5fe4a
Instructions to run a docker image on multiple ports simultaneously:
sudo docker run -p 0.0.0.0:3306:3306 -p 0.0.0.0:8543:8543 -t python-mariadb1
Here is the source code for a web project using the Python programming language in Docker, which also includes the help of the Jinja2 library, Blueprint :
At the beginning, I will write the programming code for the Docker file, this programming code can also give commands to Docker to create a templates folder.
FROM python
USER 0
WORKDIR /home
# RUN cd /home
RUN mkdir ./templates
EXPOSE 3306 8543
RUN pip install flask
RUN pip install Jinja2
RUN pip install mariadb
COPY file4.py ./
COPY file1.html ./templates
CMD ["python3", "./file4.py"]
Here is the source code for the HTML template that becomes the user interface of our program :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
</head>
<body>
<h1>Selamat Datang Di {{kota}}</h1>
</body>
</html>
Here is the Python source code for running a program that can display text on a web page. With the help of Jinja templates and routing from blueprints.
from jinja2 import Environment, FileSystemLoader
from flask import Flask, render_template
aplikasi = Flask(__name__)
@aplikasi.route('/')
def halamanPertama():
return render_template("file1.html",title="New Found Land",kota="Land")
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0',port='8543',debug='True')
Latihan 2
The following source code is the Docker file for Exercise 2 :
FROM python
USER 0
WORKDIR /home
RUN mkdir ./latihan2
RUN mkdir ./latihan2/templates
EXPOSE 3306 8543
RUN pip install flask
RUN pip install Jinja2
RUN pip install mariadb
COPY file1.py ./latihan2
COPY file1.html ./latihan2/templates
CMD ["python3", "./latihan2/file1.py"]
The HTML file for the following application interface:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Kode Data : {{kodedata}}</p>
<p>Tanggal Pendataan : {{tanggalpendataan}}</p>
<p>Bagian/Sub Bagian : {{bagiansubbagian}}</p>
<p>Kode Barang : {{kodebarang}}</p>
<p>Merek Printer : {{merekprinter}}</p>
</body>
</html>
Here is the Python source code for creating the core application of the program we made
import mariadb
import sys
import json
from jinja2 import Environment, FileSystemLoader
from flask import Flask, render_template
aplikasi = Flask(__name__)
try:
koneksi = mariadb.connect(user="steven",password="kucing",host="1.1.3.9",port=3306,database="saham")
except mariadb.Error as e:
print(f"Gagal Terkoneksi Ke : {e}")
sys.exit(1)
kursor = koneksi.cursor()
kursor.execute("SELECT kodedata,tanggalpendataan,bagiansubbagian,kodebarang,merekprinter FROM daftartintaprinter")
hasil = kursor.fetchall()
for data in hasil:
kodedata = data[0]
tanggalpendataan = data[1].strftime("%Y-%m-%d")
bagiansubbagian = data[2]
kodebarang = data[3]
merekprinter = data[4]
f = lambda s: f"dict({','.join(f'{k}={k}' for k in s.split(','))})"
kamusHasil = eval(f('kodedata,tanggalpendataan,bagiansubbagian,kodebarang,merekprinter'))
@aplikasi.route('/')
def halamanUtama():
return render_template("file1.html", **kamusHasil)
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0', port=8543, debug=True)
The following is a link to a lesson on how data transfer can happen in Flask and Jinja :
The following is the source code to receive data input from the murid1.html page and then display the input results to the hasil1.html page.
file1.py
from flask import Flask, render_template, request
aplikasi = Flask(__name__)
@aplikasi.route('/')
def murid():
return render_template('murid1.html')
@aplikasi.route('/hasil',methods = ['POST','GET'])
def hasil():
if request.method == 'POST':
hasil = request.form
return render_template("hasil1.html",hasil = hasil)
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0', port=8543, debug=True)
The following is the source code to display the results of the data entry activity performed in the form on the murid1.html page.
hasil1.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table border=1>
{% for key, value in hasil.items() %}
<tr>
<th>{{ key }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
In the following source code, we have successfully displayed the results of the input data that was performed in the HTML form in JSON format. We will use the JSON data transfer format because we will be using a RESTful API.
Latihan 6
Dockerfile
FROM python
USER 0
WORKDIR /home
RUN mkdir ./latihan6
RUN mkdir ./latihan6/templates
EXPOSE 3306 8543
RUN pip install flask
RUN pip install Jinja2
RUN pip install mariadb
COPY file1.py ./latihan6
COPY form1.html ./latihan6/templates
CMD ["python3", "./latihan6/file1.py"]
file1.py
from flask import Flask, render_template, request, jsonify, json
aplikasi = Flask(__name__)
@aplikasi.route('/')
def formulirIsiData():
return render_template('form1.html')
@aplikasi.route('/tampilData',methods = ['POST'])
def tampilkanData():
if request.method == 'POST':
# tampilkanData = request.form
# nama = request.form['nama']
# return print (tampilkanData)
# di bawah ini adalah kode yang berhasil dijalankan
# mencetak langsung ke json yang bisa di baca oleh browser
# return jsonify(tampilkanData.to_dict())
return jsonify(nama=request.form['nama'])
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0',port=8543, debug=True)
In this exercise, we successfully input data using Flask. Then, we take each data that was filled in the textbox and display it to the jinja2 template. All processes are done by clicking a button.
file1.py
from jinja2 import Template
from flask import Flask,render_template,request,json,jsonify
aplikasi = Flask(__name__)
@aplikasi.route('/')
def formUtama():
return render_template("halaman1.html")
@aplikasi.route('/tampilData', methods = ['POST'])
def tampilkanData():
if request.method == 'POST':
text1 = request.form.get('text1')
text2 = request.form.get('text2')
return render_template("halaman2.html", tampilText1=text1, tampilText2=text2)
# source code nya ini sudah bagus untuk menerima inputan dari form
if __name__ == '__main__':
aplikasi.run(host='0.0.0.0',port=8543,debug=True)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>{{ tampilText1 }}</p>
<p>{{ tampilText2 }}</p>
<!--- source code nya ini sudah bagus untuk menampilkan hasil inputan dari form -->
</body>
</html>