from contextlib import closing
with closing(psycopg2.connect(...)) as conn:
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users LIMIT 5')
for row in cursor:
print(row)
from psycopg2.pool import ThreadedConnectionPool
from psycopg2.extras import RealDictCursor
from contextlib import contextmanager
from urllib.parse import urlparse
DATABASE_URL = 'postgresql://postgres:postgres@localhost/postgres'
url = urlparse(DATABASE_URL)
pool = ThreadedConnectionPool(1, 50,
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port)
@contextmanager
def get_db_connection():
try:
connection = pool.getconn()
yield connection
finally:
pool.putconn(connection)
@contextmanager
def get_db_cursor(commit=False):
with get_db_connection() as connection:
cursor = connection.cursor(cursor_factory=RealDictCursor)
try:
yield cursor
if commit:
connection.commit()
finally:
cursor.close()
# Пример использования
with get_db_cursor() as cursor:
cursor.execute("SELECT city, temp_lo, temp_hi, date FROM weather;")
data = cursor.fetchone()
with get_db_cursor(commit=True) as cursor:
cursor.callproc("SOME_PROC_NAME")
func handleRequest(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
b := bufio.NewReader(conn)
for {
line, err := b.ReadBytes('\n')
if err != nil { // for example EOF
break
}
buf = append(buf, line...)
}
fmt.Print(string(buf))
}
func handleRequest(conn net.Conn) {
message := make([]byte, 1024)
_, error := conn.Read(message)
if error != nil {
fmt.Println(error)
os.Exit(1)
}
fmt.Println(string(message))
conn.Close()
}
const Curl = require('curl-request');
const req = new Curl();
const {auth: {BASIC}, option: {HTTPAUTH, USERNAME, PASSWORD}} = req.libcurl;
const url = 'localhost:8090/rest/api/2/issue';
const user = 'fred';
const password = 'fred';
const headers = ['Content-Type: application/json'];
const data = `{
"fields": {
"project": {
"key": "TEST"
},
"parent": {
"key": "TEST-101"
},
"summary": "Sub-task of TEST-101",
"description": "Don't forget to do this too.",
"issuetype": {
"id": "5"
}
}
}`;
req
.setOpt(HTTPAUTH, BASIC)
.setOpt(USERNAME, user)
.setOpt(PASSWORD, password)
.setHeaders(headers)
.setBody(data)
.post(url)
.then(res => { console.log(res) })
.catch(e => { console.error(e) });