· 4 years ago · Apr 21, 2021, 12:28 AM
1#!/usr/bin/env python3
2
3import requests
4import json
5from faker import Faker
6
7
8APIHOST = "http://library.demo.local"
9LOGIN = "cisco"
10PASSWORD = "Cisco123!"
11
12def getAuthToken():
13 authCreds = (LOGIN, PASSWORD)
14 r = requests.post(
15 f"{APIHOST}/api/v1/loginViaBasic",
16 auth = authCreds
17 )
18 if r.status_code == 200:
19 return r.json()["token"]
20 else:
21 raise Exception(f"Status code {r.status_code} and text {r.text}, while trying to Auth.")
22
23def addBook(book, apiKey):
24 r = requests.post(
25 f"{APIHOST}/api/v1/books",
26 headers = {
27 "Content-type": "application/json",
28 "X-API-Key": apiKey
29 },
30 data = json.dumps(book)
31 )
32 if r.status_code == 200:
33 print(f"Book {book} added.")
34 else:
35 raise Exception(f"Error code {r.status_code} and text {r.text}, while trying to add book {book}.")
36
37def deleteBook(apiKey,number):
38 r = requests.delete(
39 f"{APIHOST}/api/v1/books/"+str(number),
40 headers = {
41 "Content-type": "application/json",
42 "X-API-Key": apiKey
43 }
44 )
45 if r.status_code == 200:
46 print(f"Book {r.json()} delete.")
47 else:
48 raise Exception(f"Error code {r.status_code} and text {r.text}.")
49
50def optionAditionBook(apiKey,n,m):
51 # Using the faker module, generate random "fake" books
52 fake = Faker()
53 for i in range(n, m+1):
54 fakeTitle = fake.catch_phrase()
55 fakeAuthor = fake.name()
56 fakeISBN = fake.isbn13()
57 #book =
58 # add the new random "fake" book using the API
59 addBook({"id":i, "title": fakeTitle, "author": fakeAuthor, "isbn": fakeISBN},apiKey)
60
61def optionDeleteBook(apiKey,n,m):
62
63 for i in range(n,m+1):
64 deleteBook(apiKey,i)
65
66# Get the Auth Token Key
67apiKey = getAuthToken()
68
69print("***********************************BIENVENIDO************************************")
70while True:
71 option = int(input("Presione (1) si desea agregar libros aleatoriamente\nPresione (2) si desea eliminar libros\n"))
72 if option == 1:
73 n = int(input("Ingrese número de ID inicial(Número entero): "))
74 m = int(input("Ingrese número de ID final(Número entero): "))
75 optionAditionBook(apiKey, n,m)
76 break
77 elif option == 2:
78 n = int(input("Ingrese número de ID inicial(Número entero): "))
79 m = int(input("Ingrese número de ID final(Número entero): "))
80 optionDeleteBook(apiKey, n, m)
81 break
82 else:
83 print("El número ingresado no está dentro de las opciones propuestas.")
84
85
86
87
88
89
90
91