1
0
test-pocketbase/pocketbase.py

59 lines
2.1 KiB
Python
Raw Normal View History

2024-10-09 09:34:38 +00:00
import urllib.request
import json
from util import MultiPartForm
def authenticate_user(user, pwd):
payload = json.dumps({ "identity": user, "password": pwd }).encode()
headers = { 'Content-Type': "application/json" }
req = urllib.request.Request(url='http://127.0.0.1:8090/api/collections/users/auth-with-password', headers=headers, data=payload, method='POST')
with urllib.request.urlopen(req) as f:
assert f.status == 200
res = f.read().decode()
return json.loads(res)["token"]
def update_user_name(user_id, name, auth_token):
payload = json.dumps({"name": name}).encode()
headers = {
'Content-Type': "application/json",
'Authorization': f'Bearer {auth_token}'
}
req = urllib.request.Request(url=f"http://127.0.0.1:8090/api/collections/users/records/{user_id}", headers=headers, data=payload, method="PATCH")
with urllib.request.urlopen(req) as f:
assert f.status == 200
def set_user_avatar(user_id, file, auth_token):
form = MultiPartForm()
#form.add_field("name", "tototototo")
form.add_file("avatar", file.name, file)
payload = bytes(form)
req = urllib.request.Request(url=f"http://127.0.0.1:8090/api/collections/users/records/{user_id}", data=payload, method="PATCH")
req.add_header("Authorization", f"Bearer {auth_token}")
req.add_header('Content-type', form.get_content_type())
req.add_header('Content-length', len(payload))
#print(req.headers)
parts = payload.split(b"\r\n")
for i, data in enumerate(parts):
if i > 3:
print(f"{data[:10].hex(" ")}... ({str(len(data)//1024) + "kb" if len(data) > 1024 else str(len(data)) + "bytes"}.)")
else:
print(data)
with urllib.request.urlopen(req) as f:
assert f.status == 200
print(f.read().decode())
def main():
auth_token = authenticate_user("azerty", "12345678")
azerty_user_id = "f3b7xs6kjeazhaj"
#update_user_name(azerty_user_id, "new_name", auth_token)
set_user_avatar(azerty_user_id, open("test.jpg", "rb"), auth_token)
if __name__ == "__main__":
main()