Cara menggunakan python requests port

I'm attempting to make use of cgminer's API using Python. I'm particularly interested in utilizing the requests library.

Show

I understand how to do basic things in requests, but cgminer wants to be a little more specific. I'd like to shrink

import socket
import json

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 4028))

sock.send(json.dumps({'command': 'summary'}))

using requests instead.

How does one specify the port using that library, and how does one send such a json request and await a response to be stored in a variable?

asked Aug 30, 2014 at 13:29

3

As someone who has learned some of the common pitfalls of python networking the hard way, I'm adding this answer to emphasize an important-but-easy-to-mess-up point about the 1st arg of requests.get():

localhost is an alias which your computer resolves to 127.0.0.1, the IP address of its own loopback adapter. foo.com is also an alias, just one that gets resolved further away from the host.

requests.get('foo.com:4028')                #<--fails
requests.get('http://foo.com:4028')         #<--works usually  

& for loopbacks:

requests.get('http://127.0.0.1:4028')       #<--works
requests.get('http://localhost:4028')       #<--works

this one requires import socket & gives you the local ip of your host (aka, your address within your own LAN); it goes a little farther out from the host than just calling localhost, but not all the way out to the open-internet:

requests.get('http://{}:4028'.format(socket.gethostbyname(socket.gethostname())))  #<--works

answered Apr 7, 2017 at 23:04

Cara menggunakan python requests port

Rob TruxalRob Truxal

5,1883 gold badges19 silver badges39 bronze badges

4

You can specify the port for the request with a colon just as you would in a browser, such as r = requests.get('http://localhost:4028'). This will block until a response is received, or until the request times out, so you don't need to worry about awaiting a response.

You can send JSON data as a POST request using the requests.post method with the data parameter, such as

import json, requests
payload = {'command': 'summary'}
r = requests.post('http://localhost:4028', data=json.dumps(payload))

Accessing the response is then possible with r.text or r.json().

Note that requests is an HTTP library - if it's not HTTP that you want then I don't believe it's possible to use requests.

answered Aug 30, 2014 at 14:02

KkelkKkelk

1366 bronze badges

HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.

Request with headers

Requests do not change its behavior at all based on which headers are specified. The headers are simply passed on into the final request. All header values must be a string, bytestring, or Unicode. While permitted, it’s advised to avoid passing Unicode header values. We can make requests with the headers we specify and by using the headers attribute we can tell the server with additional information about the request.

Headers can be Python Dictionaries like,  { “Name of Header”: “Value of the Header” }

The Authentication Header tells the server who you are.  Typically, we can send the authentication credentials through the Authorization header to make an authenticated request.

Example:

Headers = { “Authorization” : ”our_unique_secret_token” }

response = request.post(“https://example.com/get-my-account-detail”, headers=Headers)

Request Object Structure

Request with body

POST requests pass their data through the message body, The Payload will be set to the data parameter. data parameter takes a dictionary, a list of tuples, bytes, or a file-like object. You’ll want to adapt the data you send in the body of your request to the specified URL.

Syntax:

requests.post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

Given below are few implementations to help understand the concept better.

Example 1: Sending requests with data as a payload

Python3

import requests

data = {

    "id": 1001,

    "name": "geek",

    "passion": "coding",

}

response = requests.post(url, json=data)

print("Status Code", response.status_code)

print("JSON Response ", response.json())

Output:

Example 2: Sending requests with JSON data and headers

Python

import requests

import json

headers = {"Content-Type": "application/json; charset=utf-8"}

data = {

    "id": 1001,

    "name": "geek",

    "passion": "coding",

}

response = requests.post(url, headers=headers, json=data)

print("Status Code", response.status_code)

print("JSON Response ", response.json())

Output:

Halo teman teman pada artikel kali ini kita akan belajar library requests di python, pastinya anda sudah tau makanya anda cari belajar library requests dasar di python. Oke langsung saja ke dasar dasarnya.

> Install Library Requests

[email protected]#: pip install requests

Fungsi di atas adalah menginstall library requests di python. Kalian bisa menginstallnya melalui terminal.

> Import Library Requests Ke Script

import requests

Fungsi kode di atas adalah mengimport module requests yang sudah kita install tadi.

> Permintaan GET

>>> requests.get("www.malastech.com")

Metode GET berfungsi untuk mengambil data dari sumber yang kita tentukan, Untuk responnya ada di bawah ini.

> Respon

Pertama kita buat variabel lalu di dalamnya isi dengan Permintaan GET tadi.

respon = requests.get("malastech.com")

Respon : Status Kode

Pada respon status kode ini kalian bisa mengetahui website tersebut aktif atau tidak.

print(respon.status_code)

Hasilnya

$ 200

Respon : Kandungan / Content

Pada respon kandungan ini kalian bisa mengambil dari json,text.

Content

Semua content yang ada di website akan langsung di ambil

print(respon.content)

Text 

Ini sebenernya hampir sama dengan yang content tadi.

print(respon.text)

JSON

Pada respon kali ini jika kamu ingin ambil json pada website contohnya mengambil data di rest APi

print(respon.json)

> Headers

Pada respon header ini kalian bisa mengambil contohnya content type dan lain lain.

print(respon.headers)

Content Type

print(respon.headers['content-type'])

 > Metode HTTP

Tidak hanya GET, POST tapi masih banyak metode httpnya dengan di awali dengan GET.

print(respon.put)

print(respon.post)

print(respon.head)

print(respon.delete)

print(respon.patch)

print(respon.options)

Fungsi Fungsi Metode HTTP Di Atas

PUT

PUT adalah untuk meletakkan atau memperbarui sumber daya di server: ... Sebaliknya HTTP sudah menyediakan mekanisme dan semantik untuk CRUD Sumber Daya (misalnya perintah) melalui metode HTTP. HTTP adalah protokol dan bukan hanya beberapa layanan terowongan data.

sumber : https://bit.ly/3nTRcMz

POST

POST pada HTTP, POST digunakan untuk mengirim data yang biasanya di gunakan untuk menambah/merubah data pada server.

HEAD

HTTP header adalah bagian inti dari permintaan dan respon HTTP ini, dan mereka membawa informasi tentang browser klien, halaman yang diminta, server dan banyak lagi.

DELETE

DELETE adalah untuk menghapus sumber permintaan: ... Metode DELETE meminta server asal menghapus sumber daya yang diidentifikasi oleh Request-URI.

PATCH

Metode PATCH meminta agar serangkaian perubahan yang dijelaskan dalam entitas permintaan diterapkan ke sumber daya yang diidentifikasi oleh Request-URI

Nah sudah pada tau kan dasar dasar nya library requests, dan juga mohon maaf jika masih ada yang kurang, ditunggu artikel selanjutnya, Matur Nuwun:)

All Link Sumber : 

-https://qastack.id/programming/28459418/use-of-put-vs-patch-methods-in-rest-api-real-life-scenarios

- https://qastack.id/programming/12142652/what-is-the-usefulness-of-put-and-delete-http-request-methods#:~:text=DELETE%20adalah%20untuk%20menghapus%20sumber,yang%20diidentifikasi%20oleh%20Request-URI.

- https://code.tutsplus.com/id/tutorials/http-headers-for-dummies--net-8039#:~:text=HTTP%20header%20adalah%20bagian%20inti,diminta%2C%20server%20dan%20banyak%20lagi.

- https://jagowebdev.com/memahami-get-dan-post-pada-php-dan-http/#:~:text=Begitu%20juga%20dengan%20istilah%20POST,menambah%2Fmerubah%20data%20pada%20server.

- https://qastack.id/programming/12142652/what-is-the-usefulness-of-put-and-delete-http-request-methods#:~:text=PUT%20adalah%20untuk%20meletakkan%20atau%20memperbarui%20sumber%20daya%20di%20server:&amp;text=Sebaliknya%20HTTP%20sudah%20menyediakan%20mekanisme,hanya%20beberapa%20layanan%20terowongan%20data.