Commit cf60a7ac60d2e6286274a9a407a63f6792a39fe6

Authored by pedro
1 parent 922ad5da
Exists in master

post no lighbase funcionando corretamente, porém, funcionamento do put é incerto

git-svn-id: http://svn.brlight.net/svn/lightbase-neo/trunk/LBBulk@825 29b92fdf-8c97-4584-b987-84e8d3c556fa
development.ini
1 -###  
2 -# app configuration  
3 -# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html  
4 -###  
5 -  
6 [app:main] 1 [app:main]
7 use = egg:LBBulk 2 use = egg:LBBulk
8 3
@@ -14,7 +9,7 @@ pyramid.default_locale_name = en @@ -14,7 +9,7 @@ pyramid.default_locale_name = en
14 pyramid.includes = 9 pyramid.includes =
15 pyramid_tm 10 pyramid_tm
16 11
17 -sqlalchemy.url = postgresql://postgres:postgres@10.1.0.152/projeto1 12 +sqlalchemy.url = postgresql://rest:rest@localhost/projeto1
18 13
19 domain = http://localhost/lbgenerator 14 domain = http://localhost/lbgenerator
20 base_name = WMI 15 base_name = WMI
@@ -48,7 +43,7 @@ handlers = @@ -48,7 +43,7 @@ handlers =
48 qualname = lbbulk 43 qualname = lbbulk
49 44
50 [logger_sqlalchemy] 45 [logger_sqlalchemy]
51 -level = INFO 46 +level = WARN
52 handlers = 47 handlers =
53 qualname = sqlalchemy.engine 48 qualname = sqlalchemy.engine
54 # "level = INFO" logs SQL queries. 49 # "level = INFO" logs SQL queries.
lbbulk/config/routing.py
@@ -10,5 +10,5 @@ def make_routes(config): @@ -10,5 +10,5 @@ def make_routes(config):
10 config.add_static_view('static', 'static', cache_max_age=3600) 10 config.add_static_view('static', 'static', cache_max_age=3600)
11 config.add_route('home', '/') 11 config.add_route('home', '/')
12 config.add_restful_routes('sources', BulkSourcesContextFactory) 12 config.add_restful_routes('sources', BulkSourcesContextFactory)
13 - config.add_restful_routes('registro', BulkUploadContextFactory, 13 + config.add_restful_routes('reg', BulkUploadContextFactory,
14 view=RegCustomView) 14 view=RegCustomView)
15 \ No newline at end of file 15 \ No newline at end of file
lbbulk/model/BulkUpload.py
@@ -9,25 +9,26 @@ bulk_upload = Table('lb_bulk_upload', metadata, @@ -9,25 +9,26 @@ bulk_upload = Table('lb_bulk_upload', metadata,
9 Column('chave_externa', String, nullable=False), 9 Column('chave_externa', String, nullable=False),
10 Column('id_source', Integer, 10 Column('id_source', Integer,
11 ForeignKey('lb_bulk_sources.id_source'), 11 ForeignKey('lb_bulk_sources.id_source'),
12 - nullable=False) 12 + nullable=False),
  13 + extend_existing=True
13 ) 14 )
14 15
15 # map to it 16 # map to it
16 class BulkUpload(Base): 17 class BulkUpload(Base):
17 __table__ = bulk_upload 18 __table__ = bulk_upload
18 19
  20 + def verifica_registro(data):
  21 + q = session.query(BulkUpload).filter_by(id_source=data['id_source'], chave_externa=data['json_reg']['id_reg'] )
  22 + registro_existe = q.first()
  23 + return registro_existe
  24 +
  25 +
19 class BulkUploadContextFactory(SQLAlchemyORMContext): 26 class BulkUploadContextFactory(SQLAlchemyORMContext):
20 entity = BulkUpload 27 entity = BulkUpload
21 28
22 def session_factory(self): 29 def session_factory(self):
23 return session 30 return session
24 31
25 - def create_member(self, data):  
26 - member = self.entity(**data)  
27 - self.session.add(member)  
28 - self.session.commit()  
29 - return member  
30 -  
31 def get_member_id_as_string(self, member): 32 def get_member_id_as_string(self, member):
32 id = self.get_member_id(member) 33 id = self.get_member_id(member)
33 return json.dumps(id, cls=self.json_encoder) 34 return json.dumps(id, cls=self.json_encoder)
34 \ No newline at end of file 35 \ No newline at end of file
lbbulk/view/restfulview.py
1 from pyramid_restler.view import RESTfulView 1 from pyramid_restler.view import RESTfulView
  2 +from pyramid.response import Response
  3 +from lbbulk.model.BulkUpload import BulkUpload
2 import configparser 4 import configparser
3 import json 5 import json
4 import requests 6 import requests
5 7
6 class RegCustomView(RESTfulView): 8 class RegCustomView(RESTfulView):
  9 +
  10 + def create_member(self):
  11 + member = self.context.create_member(self._get_data())
  12 + id = self.context.get_member_id_as_string(member)
  13 + headers = {'Location': '/'.join((self.request.path, id))}
  14 + return Response(status=201, headers=headers)
  15 +
7 def _get_data(self): 16 def _get_data(self):
8 """ Read json data from the post sent by some source """ 17 """ Read json data from the post sent by some source """
9 - print('\n\n\n\n\n\n\n\n\n\n\n\n')  
10 content_type = self.request.content_type 18 content_type = self.request.content_type
11 if content_type == 'application/json': 19 if content_type == 'application/json':
12 data = json.loads(self.request.body) 20 data = json.loads(self.request.body)
@@ -22,20 +30,30 @@ class RegCustomView(RESTfulView): @@ -22,20 +30,30 @@ class RegCustomView(RESTfulView):
22 def send_to_lightbase(self, data): 30 def send_to_lightbase(self, data):
23 """ Sends the register to a lightbase table and returns a dict 31 """ Sends the register to a lightbase table and returns a dict
24 with the external key and lighbase's id_reg """ 32 with the external key and lighbase's id_reg """
  33 + data['json_reg'] = json.loads(data['json_reg'])
  34 + # converte os filhos pra dicts
  35 + existente = BulkUpload.verifica_registro(data)
  36 + # print(existente.id_reg)
  37 + print('\n\n\n\n\n\n\n\n\n\n')
25 registro = self.is_error(data) 38 registro = self.is_error(data)
26 id_source = registro['id_source'] 39 id_source = registro['id_source']
27 registro.pop('id_source', None) 40 registro.pop('id_source', None)
28 - registro['json_reg'] = json.loads(registro['json_reg'])  
29 chave_externa = registro['json_reg']['id_reg'] 41 chave_externa = registro['json_reg']['id_reg']
30 registro['json_reg'].pop('id_reg', None) 42 registro['json_reg'].pop('id_reg', None)
  43 + registro['json_reg'] = json.dumps(registro['json_reg'])
31 url = self.get_url_lightbase() 44 url = self.get_url_lightbase()
32 - r = requests.post(url, data=registro)  
33 - id_reg = r.json()  
34 - data = {  
35 - 'id_source':id_source,  
36 - 'id_reg':id_reg,  
37 - 'chave_externa':chave_externa  
38 - } 45 + if existente is None:
  46 + r = requests.post(url, data=registro)
  47 + id_reg = self.is_error_resp(r.json())
  48 + data = {
  49 + 'id_source':id_source,
  50 + 'id_reg':id_reg,
  51 + 'chave_externa':chave_externa
  52 + }
  53 + else:
  54 + r = requests.put(url, data=registro)
  55 + id_reg = existente
  56 + data = None
39 return data 57 return data
40 58
41 def get_url_lightbase(self): #TODO 59 def get_url_lightbase(self): #TODO
@@ -46,4 +64,9 @@ class RegCustomView(RESTfulView): @@ -46,4 +64,9 @@ class RegCustomView(RESTfulView):
46 return url 64 return url
47 65
48 def is_error(self,data): #TODO 66 def is_error(self,data): #TODO
49 - return data  
50 \ No newline at end of file 67 \ No newline at end of file
  68 + return data
  69 +
  70 + def is_error_resp(self,r):
  71 + if type(r) is dict:
  72 + raise TypeError('Lightbase error ' + str(r['_status']) + ': ' + r['_error_message'])
  73 + return r
51 \ No newline at end of file 74 \ No newline at end of file