jsonAndRequest.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import json
  2. import requests
  3. import config
  4. import ast
  5. import logging
  6. import loggingConfig
  7. import pprint
  8. #Тестовый класс User и Address (ВАЖНО!!!) поля классов должны называться также как и поля json объекта
  9. '''
  10. #Full json order example
  11. https://wiki.sharix-app.org/doku.php/open/tech/dev/sharix_open_-_primery_json
  12. {
  13. "ticket": 123,
  14. "status": 111,
  15. "priority": 1, (фишка для сортировки)
  16. "title": "123",
  17. "note": "123", (чтото похожее на json для техподдержки)
  18. "due_date": 2023-05-15T17:16:22.955601Z, (для очистка старых заявок, чтобы система не переполнялась)
  19. "id_metaservice": 1,
  20. "is_global": false,
  21. "is_visible": false,
  22. "service": 1,
  23. "service_type": 1,
  24. "status_changed_date": "2023-05-15T17:16:22.955601Z", (для техподдержки когда было изменено)
  25. "time_placed": "2023-05-15T16:40:32.179777Z",
  26. "time_start": "2023-05-15T16:40:32.179777Z", (когда долже наначаться по заявке)
  27. "time_start_predicted": "2023-05-15T16:40:32.179777Z",
  28. "time_finish_predicted": "2023-05-15T16:40:32.179777Z",
  29. "time_start_real": "2023-05-15T16:40:32.179777Z", ()
  30. "time_finish_real": "2023-05-15T16:40:32.179777Z",
  31. "order_place_type": "address",
  32. "order_place_start": "р-н Беговой",
  33. "order_place_start_gps": "55.751941, 37.607513",
  34. "order_place_start_sector": 4,
  35. "order_place_start_real": "р-н Беговой",
  36. "order_place_start_real_gps": "55.751941, 37.607513",
  37. "order_place_finish_predicted": "р-н Мещанский",
  38. "order_place_finish_predicted_gps": "55.751941, 37.607513",
  39. "order_place_finish_sector": 4,
  40. "order_place_finish_real": "р-н Мещанский",
  41. "order_place_finish_real_gps": "55.751941, 37.607513",
  42. "predicted_price": 1000,
  43. "real_price": 1001,
  44. "payment_transaction_id": 1, (локальное, для оплаты)
  45. "rating_id": 1,
  46. "provider": 1, (приёмник, тот, кто приезжает)
  47. "provider_screen_name": "Vasya Ispolnitelev",
  48. "receiver": 1,
  49. "receiver_screen_name": "Marfa Clientovna",
  50. "client_id": 1, (инициатор - клиент - источник)
  51. "client_screen_name": "Fedor Client",
  52. "resource_id": 1, (машина привязанная к заказу, в друге - помещение (то, что предоставляют компании партнёры))
  53. "attempts": null (клиенту не хочется бесконечно ждать. Кол-во попыток для какойто операции)
  54. }
  55. '''
  56. #надо адаптировать класс к новому формату JSON
  57. class Order(object):
  58. def __init__(self, ticket, state, id_metaservice, is_global, is_visible, service, service_type, time_placed, time_start=None, time_start_predicted=None, time_finish_predicted=None, time_start_real=None, time_finish_real=None, order_place_start=None, order_place_start_gps=None, order_place_start_real=None, order_place_start_real_gps=None, order_place_finish_predicted=None, order_place_finish_predicted_gps=None, order_place_finish_real=None, order_place_finish_real_gps=None, predicted_price=None, real_price=None, payment_transaction_id=None, rating_id=None, provider=None, provider_screen_name=None, receiver=None, receiver_screen_name=None, client_id=None, resource_id=None):
  59. self.ticket = ticket
  60. self.state = state
  61. self.id_metaservice = id_metaservice
  62. self.is_global = is_global
  63. self.is_visible = is_visible
  64. self.service = service
  65. self.service_type = service_type
  66. self.time_placed = time_placed
  67. self.time_start = time_start
  68. self.time_start_predicted = time_start_predicted
  69. self.time_finish_predicted = time_finish_predicted
  70. self.time_start_real = time_start_real
  71. self.time_finish_real = time_finish_real
  72. self.order_place_start = order_place_start
  73. self.order_place_start_gps = order_place_start_gps
  74. self.order_place_start_real = order_place_start_real
  75. self.order_place_start_real_gps = order_place_start_real_gps
  76. self.order_place_finish_predicted = order_place_finish_predicted
  77. self.order_place_finish_predicted_gps = order_place_finish_predicted_gps
  78. self.order_place_finish_real = order_place_finish_real
  79. self.order_place_finish_real_gps = order_place_finish_real_gps
  80. self.predicted_price = predicted_price
  81. self.real_price = real_price
  82. self.payment_transaction_id = payment_transaction_id
  83. self.rating_id = rating_id
  84. self.provider = provider
  85. self.provider_screen_name = provider_screen_name
  86. self.receiver = receiver
  87. self.receiver_screen_name = receiver_screen_name
  88. self.client_id = client_id
  89. self.resource_id = resource_id
  90. #доделать до конца по аналогии с закоммиченным json
  91. def __str__(self):
  92. return "{0}, {1}, {2}, {3}, {4}, {5}, {6},\n{7}, {8}, {9}, {10}, {11}, {12},\n{13}, {14}, {15}, {16}, {17}, {18}, {19}, {20},\n{21}, {22}, {23}, {24},\n{25}, {26}, {27}, {28}, {29}, {30}".format(self.ticket, self.state, self.id_metaservice, self.is_global, self.is_visible, self.service, self.service_type, self.time_placed, self.time_start, self.time_start_predicted, self.time_finish_predicted, self.time_start_real, self.time_finish_real, self.order_place_start, self.order_place_start_gps, self.order_place_start_real, self.order_place_start_real_gps, self.order_place_finish_predicted, self.order_place_finish_predicted_gps, self.order_place_finish_real, self.order_place_finish_real_gps, self.predicted_price, self.real_price, self.payment_transaction_id, self.rating_id, self.provider, self.provider_screen_name, self.receiver, self.receiver_screen_name, self.client_id, self.resource_id)
  93. #\n добавляете в местах с пустой строкой в шаблоне
  94. #ticket json example
  95. '''
  96. {
  97. "id": 2,
  98. "status": 111,
  99. "created_date": "2023-05-15",
  100. "status_changed_date": "2023-05-15T17:16:22.955601Z",
  101. "priority": 0,
  102. "title": "Test",
  103. "note": "{\n \n \"ticket\": 1,\n \"state\": 1,\n \"id_metaservice\": 1,\n \"is_global\": false,\n \"is_visible\": false,\n \"service\": 1,\n \"service_type\": 1,\n\n \"time_placed\": 1}"
  104. "due_date": "2023-05-15",
  105. "task_list": 10,
  106. "created_by": 1,
  107. "type": 1,
  108. "assigned_to": 1
  109. }
  110. '''
  111. #ticket minimal example
  112. '''
  113. {
  114. "id": 2,
  115. "status": 111,
  116. "created_date": "2023-05-15",
  117. "status_changed_date": "2023-05-15T17:16:22.955601Z",
  118. "priority": 0,
  119. "title": null,
  120. "note": null,
  121. "due_date": null,
  122. "task_list": 10,
  123. "created_by": 1,
  124. "type": 1,
  125. "assigned_to": null
  126. }
  127. '''
  128. class OrderTicket(object):
  129. def __init__(self, id, status, created_date, status_changed_date, priority, title=None, note=None, due_date=None, task_list=None, created_by=None, type=None, assigned_to=None):
  130. self.id = id
  131. self.status = status
  132. self.created_date = created_date
  133. self.status_changed_date = status_changed_date
  134. self.priority = priority
  135. self.title = title
  136. self.note = note
  137. self.due_date = due_date
  138. self.task_list = task_list
  139. self.created_by = created_by
  140. self.type = type
  141. self.assigned_to = assigned_to
  142. def __str__(self):
  143. return "{0}, {1}, {2}, {3}, {4}, {5}, {6},\n{7}, {8}, {9}, {10}, {11}\n".format(self.id, self.status, self.created_date, self.status_changed_date, self.priority, self.title, self.note, self.due_date, self.task_list, self.created_by, self.type, self.assigned_to)
  144. #Функция преобразования json в объект класса Order
  145. def jsonToOrder(jsonstring) -> Order:
  146. jsonObj = json.loads(jsonstring)
  147. # print(jsonObj)
  148. logging.debug(jsonObj)
  149. u = Order(**jsonObj)
  150. return u
  151. #Функция преобразования json в объект класса OrderTicket
  152. def jsonToOrderTicket(jsonstring) -> OrderTicket:
  153. # print (jsonstring)
  154. logging.debug(jsonstring)
  155. jsonObj = json.loads(jsonstring)
  156. # print(jsonObj)
  157. logging.debug(jsonObj)
  158. u = OrderTicket(**jsonObj)
  159. return u
  160. #Функция обращения к апи и получение токена
  161. def requestGetToken(login, password, url) -> str:
  162. #login = "79876543210"
  163. #password = "admin12345@"
  164. #url = "https://user.sharix-app.org/auth/token/login/"
  165. data = {
  166. "password": password,
  167. "phone_number": login
  168. }
  169. response = requests.post(url, json=data)
  170. result = response.json()
  171. return result['auth_token']
  172. #Функция обращения к апи и получение токена
  173. def createUser(username, phone, password, url) -> str:
  174. data = {
  175. "username": username,
  176. "phone_number": phone,
  177. "password": password
  178. }
  179. response = requests.post(url, json=data)
  180. result = response.json()
  181. return result
  182. #Функция обращения к апи и получение списка пользователей
  183. def requestGetListUser():
  184. auth_token=requestGetToken()
  185. # print(auth_token)
  186. logging.debug(f"Auth token: {auth_token}")
  187. headers = {'Authorization': f'Token {auth_token}'}
  188. url = 'https://user.sharix-app.org/platform/api/sharix-users/'
  189. response = requests.get(url, headers=headers)
  190. # print(response)
  191. logging.debug(response)
  192. # print(response.json())
  193. logging.debug(f"Auth token: {response.json()}")
  194. def requestGetList(auth_token, url):
  195. #auth_token=requestGetToken(login, password, url)
  196. #print(auth_token)
  197. headers = {'Authorization': f'Token {auth_token}'}
  198. #url = 'https://user.sharix-app.org/platform/api/sharix-users/'
  199. response = requests.get(config.API_URL+"/tickets/api/tickets/?list_id=10", headers=headers)
  200. #response = requests.get(config.API_URL+"/metaservicesynced/api/orders/", headers=headers)
  201. #print(response)
  202. logging.debug(response)
  203. #return response.json()
  204. #print(response.json())
  205. logging.debug(pprint.pformat(response.json()))
  206. ordertext=response.json()
  207. startlist = []
  208. if not ordertext:
  209. # print("Empty array")
  210. logging.info("Empty array")
  211. else:
  212. for i in ordertext:
  213. # print (i, "PROCESSING")
  214. logging.debug(f"\"PROCESSING\"\n{pprint.pformat(i)}")
  215. try:
  216. orderticket = OrderTicket(**i)
  217. # print(i, "ORDER ", orderticket)
  218. # logging.debug(f"{pprint.pformat(i)}, \"ORDER\" {orderticket}")
  219. startlist.append(orderticket)
  220. logging.debug(f"\"ORDER\"\n{orderticket}")
  221. except Exception as ex:
  222. # print(ex)
  223. logging.error("Exception occurred", exc_info=True)
  224. # print (startlist)
  225. logging.debug("Startlist: " + pprint.pformat(startlist))
  226. #if ordertext is not None:
  227. # for order in ordertext:
  228. # print (order)
  229. # strorder = str(order).replace("'", '"')
  230. # strorder = strorder.replace("None", 'null')
  231. # #parsed_json = ast.literal_eval(order)
  232. # #print (parsed_json)
  233. # orderObj = jsonToOrderTicket(strorder)
  234. # print (orderObj)
  235. # startlist.append(orderObj)
  236. # #bot.bot_log(str(datetime.now())+"Заказ успешно добавлен в очередь обработки\n")
  237. #print (orderticket)
  238. return startlist
  239. уже есть:
  240. чтение
  241. создать заказ
  242. редактировать заказ целиком
  243. редактировать отдельное поле
  244. под каждую операцию отдельный запрос (универсальная ф-ция: передаётся название поля и значение)
  245. функционал: подобрать,
  246. отправлять vs создать