class TestAmbiguousRelations(TestCase): def setUp(self): super(TestAmbiguousRelations, self).setUp() self._domain = DomainConfig({ 'users': ResourceConfig(User), 'admins': ResourceConfig(User), 'groups': ResourceConfig(Group) }) def test_missing_related_resources_without_groups(self): del self._domain.resource_configs['groups'] domain_dict = self._domain.render() self.assertIn('users', domain_dict) self.assertIn('admins', domain_dict) def test_missing_related_resources(self): with self.assertRaises(ConfigException) as cm: self._domain.render() self.assertIn('Cannot determine related resource for {}' .format(Group.__name__), str(cm.exception)) def test_two_endpoints_for_one_model(self): self._domain.related_resources = { (Group, 'members'): 'users', (Group, 'admin'): 'admins' } groups_schema = self._domain.render()['groups']['schema'] self.assertEqual(groups_schema['admin']['data_relation']['resource'], 'admins')
def setUp(self): super(TestAmbiguousRelations, self).setUp() self._domain = DomainConfig({ 'users': ResourceConfig(User), 'admins': ResourceConfig(User), 'groups': ResourceConfig(Group) })
class Settings(Config): # SERVER_NAME = '0.0.0.0:6000' DEBUG = True EMBEDDING = True """ @RESOURCE_METHODS 端点 支持http 方法 如: http://demo/user @ITEM_METHODS 端点 支持http 方法 如: http://demo/user/<id> """ RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PUT', 'PATCH', 'DELETE'] URL_PREFIX = 'api' IF_MATCH = False # disable etag from http://docs.python-eve.org/en/latest/features.html#concurrency X_DOMAINS = '*' X_HEADERS = '*' HATEOAS = False ALLOW_UNKNOWN = True # for user.password_hash updated by password DATE_FORMAT = '%Y-%m-%d %H:%M:%S' STATIC_FOLDER = os.path.join(MY_ROOT_DIR, 'static') DOMAIN = DomainConfig({ 'user': ResourceConfig(User), 'role': ResourceConfig(Role), 'picture': ResourceConfig(Picture), 'order': ResourceConfig(Order), 'food': ResourceConfig(Food), 'room': ResourceConfig(Room), 'story': ResourceConfig(Story), 'contact': ResourceConfig(Contact), 'news': ResourceConfig(News), }).render() # dynamic relation cannot be json serialized , relationship backref => model name # DOMAIN['user']['datasource']['projection']['address'] = 0 DOMAIN['user']['schema']['role']['data_relation']['embeddable'] = True DOMAIN['room']['schema']['story']['schema']['data_relation']['embeddable'] = True DOMAIN['order']['schema']['room']['schema']['data_relation']['embeddable'] = True # DOMAIN['story']['item_methods'] = ['GET', 'PUT', 'PATCH'] DOMAIN['contact']['item_methods'] = ['GET', 'PUT', 'PATCH'] OPLOG = True OPLOG_NAME = 'OpLog' OPLOG_ENDPOINT = 'OpLog' OPLOG_RETURN_EXTRA_FIELD = False OPLOG_METHODS = ['DELETE', 'POST', 'PATCH', 'PUT', 'GET'] sys.modules[OPLOG_NAME] = OpLog def load_settings(self): return {name: getattr(self, name) for name in dir(self) if not name.startswith('__') and not hasattr(getattr(self, name), '__call__')}
def main(config_args={}): import argparse parser = argparse.ArgumentParser() parser.add_argument('-d', '--database_type', type=str, default='sqlite', help='specify the database backend', choices=['sqlite', 'mysql']) config_args.update(vars( parser.parse_args())) # pargs, unparsed = parser.parse_known_args() cwd = os.getcwd() print("Using current working directory...'{:}'".format(cwd)) SETTINGS = { 'DEBUG': True, 'DATE_FORMAT': '%Y-%m-%d %H:%M:%S', # 2017-02-01 10:00:00 'PAGINATION_LIMIT': 250, 'SQLALCHEMY_DATABASE_URI': default_uri(config_args['database_type'], cwd), 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'JSON_ARGUMENT': 'callback', 'RESOURCE_METHODS': ['GET'], 'DOMAIN': DomainConfig({ 'legislator': ResourceConfig(Legislator), 'vote': ResourceConfig(Votes), 'bill': ResourceConfig(Bills), 'sponsor': ResourceConfig(BillSponsor), 'role': ResourceConfig(Roles), 'action': ResourceConfig(Actions), 'subject': ResourceConfig(DistrictSubjects), 'word': ResourceConfig(DistrictWords), 'subject_tag': ResourceConfig(Subjects), 'word_tag': ResourceConfig(Words) }).render() } app = Eve(auth=None, settings=SETTINGS, validator=ValidatorSQL, data=SQL) # bind SQLAlchemy db = app.data.driver Base.metadata.bind = db.engine db.Model = Base db.create_all() # using reloader will destroy the in-memory sqlite db app.run(debug=True, use_reloader=False)
class Settings(Config): # SERVER_NAME = '0.0.0.0:6000' DEBUG = True EMBEDDING = True PAGINATION_DEFAULT = 1000 PAGINATION_LIMIT = 1000 """ @RESOURCE_METHODS 端点 支持http 方法 如: http://demo/user @ITEM_METHODS 端点 支持http 方法 如: http://demo/user/<id> """ RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PUT', 'PATCH', 'DELETE'] URL_PREFIX = 'api' IF_MATCH = False # disable etag from http://docs.python-eve.org/en/latest/features.html#concurrency X_DOMAINS = '*' X_HEADERS = '*' HATEOAS = False ALLOW_UNKNOWN = True # for user.password_hash updated by password DATE_FORMAT = '%Y-%m-%d %H:%M:%S' STATIC_FOLDER = os.path.join(MY_ROOT_DIR, 'static') DOMAIN = DomainConfig({ 'user': ResourceConfig(User), 'role': ResourceConfig(Role), 'address': ResourceConfig(Address), }).render() # dynamic relation cannot be json serialized , relationship backref => model name DOMAIN['user']['datasource']['projection']['address'] = 0 DOMAIN['address']['schema']['user']['data_relation']['embeddable'] = True def load_settings(self): return {name: getattr(self, name) for name in dir(self) if not name.startswith('__') and not hasattr(getattr(self, name), '__call__')}
def register_resources(app): """Register the resources defined in `instance.config.schema`. Please it's docstring for understanding how to define resource schema. """ from .db import Base from .configs.schema import EVE_SQL_SCHEMA from eve_sqlalchemy.config import DomainConfig, ResourceConfig tables_found = {} for table, options in EVE_SQL_SCHEMA: for key in Base._decl_class_registry: if hasattr(Base._decl_class_registry[key], '__tablename__') and \ Base._decl_class_registry[key].__tablename__ == table: tables_found[table] = ResourceConfig( Base._decl_class_registry[key] ) break rendered_schema = DomainConfig(tables_found).render() for table, options in EVE_SQL_SCHEMA: update_dict( rendered_schema[table], options, append=app.config.get('DOMAIN_SCHEMA_APPEND', False) ) # app.logger.info(rendered_schema) db = app.data.driver Base.metadata.bind = db.engine db.Model = Base # finally we update the schema for eve application for t in rendered_schema: app.register_resource(t, rendered_schema[t])
def get_DOMAIN() -> dict: """ Render all cerberus domains for data model resources (i.e., any model extending `CommonColumns`). """ domain_config = {} domain_config["new_users"] = ResourceConfig(Users) domain_config["trial_metadata"] = ResourceConfig(TrialMetadata, id_field="trial_id") for model in [Users, UploadJobs, Permissions, DownloadableFiles]: domain_config[model.__tablename__] = ResourceConfig(model) # Eve-sqlalchemy needs this to be specified explicitly for foreign key relations related_resources = { (Permissions, "to_user"): "users", (Permissions, "by_user"): "users", (Permissions, "trial"): "trial_metadata", (UploadJobs, "uploader"): "users", (DownloadableFiles, "trial"): "trial_metadata", } domain = DomainConfig(domain_config, related_resources).render() # Restrict operations on the 'new_users' resource del domain["new_users"]["schema"]["role"] del domain["new_users"]["schema"]["approval_date"] domain["new_users"]["item_methods"] = [] domain["new_users"]["resource_methods"] = ["POST"] # Make downloadable_files read-only domain["downloadable_files"]["allowed_methods"] = ["GET"] domain["downloadable_files"]["allowed_item_methods"] = ["GET"] # Add the download_link field to the downloadable_files schema domain["downloadable_files"]["schema"]["download_link"] = {"type": "string"} return domain
}, 'license': { 'name': 'BSD', 'url': 'https://github.com/Dallas-Makerspace/DMS-API/blob/master/LICENSE', }, 'schemes': ['http', 'https'], }, 'RENDERERS': ['eve.render.JSONRenderer'], 'X_DOMAINS': "*", 'X_HEADERS': "*", 'X_ALLOW_CREDENTIALS': True, # backend schema 'DOMAIN': DomainConfig({ 'people': ResourceConfig(People) }).render() } def main(): app = Eve(auth=None, settings=SETTINGS, validator=ValidatorSQL, data=SQL) app.register_blueprint(swagger) # bind SQLAlchemy db = app.data.driver Base.metadata.bind = db.engine db.Model = Base db.create_all() # Insert some example data in the db
# The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: # Using sqlalchemy classes to generate schema DOMAIN = DomainConfig({ 'logIpInfo': ResourceConfig(domain.logIpInfo), 'logIpCnt': ResourceConfig(domain.logIpCnt), 'regionCity': ResourceConfig(domain.regionCity), 'clientProfile': ResourceConfig(domain.clientProfile), 'clientAuth': ResourceConfig(domain.clientAuth), 'clientLogIpInfo': ResourceConfig(domain.clientLogIpInfo), 'paysClient': ResourceConfig(domain.paysClient), 'rubrics': ResourceConfig(domain.rubrics), 'staticPages': ResourceConfig(domain.staticPages), 'analiticRubrics': ResourceConfig(domain.analiticRubrics), 'sourceParse': ResourceConfig(domain.sourceParse), 'parseLog': ResourceConfig(domain.parseLog), 'chatMessage': ResourceConfig(domain.chatMessage), 'chatStatuses': ResourceConfig(domain.chatStatuses), 'calendar': ResourceConfig(domain.calendar), 'services': ResourceConfig(domain.services), 'usersCompany': ResourceConfig(domain.usersCompany), 'usersLoginInfo': ResourceConfig(domain.usersLoginInfo), 'settings': ResourceConfig(domain.settings) }).render()
DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///F:/geyunxiang/mmdps_git/server/apiserver/mmdpdb.db' SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] # pagination PAGINATION = False # datetime DATE_FORMAT = '%Y-%m-%dT%H:%M:%S' #SQLALCHEMY_ECHO = True #SQLALCHEMY_RECORD_QUERIES = True DOMAIN = DomainConfig({ 'people': ResourceConfig(Person), 'mriscans': ResourceConfig(MRIScan), 'motionscores': ResourceConfig(MotionScore), 'strokescores': ResourceConfig(StrokeScore), 'groups': ResourceConfig(Group), 'mrinachines': ResourceConfig(MRIMachine) }).render() # custom settings MY_STORAGE_URLBASE = rootconfig.server.storage MY_STORAGE_AUTH = ('mmdpdata', '123') MY_FEATURE_STORAGE_URLBASE = rootconfig.server.featurestorage MY_FEATURE_STORAGE_AUTH = ('mmdpdata', '123') MY_FEATURE_ROOT = 'ChangGungFeatures'
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from sql import Tasks SQLALCHEMY_DATABASE_URI = 'postgresql://*****:*****@postgresql:5432/nestdb' SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] DEBUG = True tasks = ResourceConfig(Tasks) DOMAIN = DomainConfig({ 'tasks': tasks, }).render()
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from eve_sqlalchemy.examples.multiple_dbs.domain import Table1, Table2 DEBUG = True SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/db1.sqlite' SQLALCHEMY_BINDS = {'db2': 'sqlite:////tmp/db2.sqlite'} # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'table1': ResourceConfig(Table1), 'table2': ResourceConfig(Table2) }).render()
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from eve_sqlalchemy.examples.simple.tables import Invoices, People DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite://' SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'people': ResourceConfig(People), 'invoices': ResourceConfig(Invoices) }).render() # But you can always customize it: DOMAIN['people'].update({ 'item_title': 'person', 'cache_control': 'max-age=10,must-revalidate', 'cache_expires': 10, 'resource_methods': ['GET', 'POST', 'DELETE'] })
RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PATCH', 'DELETE', 'PUT'] DOMAIN = DomainConfig({ 'disabled_bulk': ResourceConfig(DisabledBulk), 'contacts': ResourceConfig(Contacts), 'invoices': ResourceConfig(Invoices), # 'versioned_invoices': versioned_invoices, 'payments': ResourceConfig(Payments), 'empty': ResourceConfig(Empty), # 'restricted': user_restricted_access, # 'peoplesearches': users_searches, # 'companies': ResourceConfig(Companies), # 'departments': ResourceConfig(Departments), 'internal_transactions': ResourceConfig(InternalTransactions), # 'ids': ids, 'login': ResourceConfig(Login), 'products': ResourceConfig(Products, id_field='sku') }).render() DOMAIN['disabled_bulk'].update({ 'url': 'somebulkurl', 'item_title': 'bulkdisabled',
file_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) DEBUG = True # Use TAOP_DB_URI env var to set database SQLALCHEMY_DATABASE_URI = os.getenv( 'TAOP_DB_URI', 'sqlite:///' + file_path + '\\db\\training.db') SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] # CORS disabled X_DOMAINS = '*' PAGINATION = False # @todo : add authentication # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'styles': ResourceConfig(Styles), 'yeast': ResourceConfig(Yeast), 'hops': ResourceConfig(Hops), 'fermentables': ResourceConfig(Fermentables), }).render()
from forge_symposia.server import env from eve_sqlalchemy.config import DomainConfig, ResourceConfig from forge_symposia.server.models import indexDB RESOURCE_METHODS = ['GET'] DOMAIN = DomainConfig({}).render() JWT_SECRET_KEY = 'python-starter-secret-key' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + env.INDEX_DB SQLALCHEMY_BINDS = {'app_db': "sqlite:///" + env.APP_DB}
from eve_sqlalchemy.config import DomainConfig, ResourceConfig import db import conf DEBUG = True URL_PREFIX = 'api' SQLALCHEMY_DATABASE_URI = conf.db_driver + '://' + conf.db_user + ':' + conf.db_password + '@' + conf.db_host + '/' + conf.db_name SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] DOMAIN = DomainConfig({ 'poster': ResourceConfig(db.Poster), 'shop': ResourceConfig(db.Shop), 'product': ResourceConfig(db.Product) }).render() DOMAIN['poster'].update({'resource_methods': []}) DOMAIN['shop'].update({ 'authentication': None, }) DOMAIN['product'].update({'authentication': None})
'ITEM_METHODS': ['GET', 'PATCH', 'PUT'], 'OPLOG': True, 'OPLOG_AUDIT': True, 'OPLOG_ENDPOINT': 'audit', 'OPLOG_METHODS': ['GET', 'DELETE', 'POST', 'PATCH', 'PUT'], 'DOMAIN': DomainConfig({ 'event': ResourceConfig(Event), 'event_meta': ResourceConfig(EventMeta), 'contact': ResourceConfig(Contact), 'contact_team': ResourceConfig(ContactTeam), 'number': ResourceConfig(Number), 'contact_number_bridge': ResourceConfig(ContactNumberBridge), 'comment': ResourceConfig(Comment), 'tag': ResourceConfig(Tag), 'comment_tag_bridge': ResourceConfig(CommentTagBridge), 'oplog': ResourceConfig(OpLog), 'totp': ResourceConfig(Totp) }).render() } SETTINGS['DOMAIN']['oplog'].update({ 'resource_methods': ['GET'], 'allowed_roles': ['superuser'] }) # Set to allow number key to be returned with events SETTINGS['DOMAIN']['contact']['schema']['numbers']['schema']['data_relation'][
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from eve_sqlalchemy.examples.foreign_primary_key.domain import Lock, Node DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite://' SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'nodes': ResourceConfig(Node), 'locks': ResourceConfig(Lock) }).render()
_created = Column(DateTime, default=func.now()) _updated = Column(DateTime, default=func.now(), onupdate=func.now()) _etag = Column(String) _id = Column(Integer, primary_key=True, autoincrement=True) class Submission(CommonColumns): __tablename__ = 'submission' url = Column(String(2000)) author = Column(String(200)) author_url = Column(String(2000)) author_icon = Column(String(2000)) comment = Column(String(5000)) DOMAIN = DomainConfig({'submission': ResourceConfig(Submission)}).render() pg_url = 'postgresql:///?host=/tmp/pg_db&dbname=template1' if 'OPENSHIFT_POSTGRESQL_DB_HOST' in os.environ: pg_url = 'postgresql://%s:%s/%s' % ( os.environ['OPENSHIFT_POSTGRESQL_DB_HOST'], os.environ['OPENSHIFT_POSTGRESQL_DB_PORT'], os.environ['OPENSHIFT_APP_NAME']) SETTINGS = { 'SQLALCHEMY_DATABASE_URI': pg_url, 'RESOURCE_METHODS': ['POST', 'GET'], 'ITEM_METHODS': ['GET'], 'DOMAIN': DOMAIN, }
# SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'users': ResourceConfig(tables.Users), 'branches': ResourceConfig(tables.Branches), 'classes': ResourceConfig(tables.Classes), 'class_students': ResourceConfig(tables.ClassStudents), 'modules': ResourceConfig(tables.Modules), 'attendances': ResourceConfig(tables.Attendances), 'attendances_tutors': ResourceConfig(tables.AttendancesTutors), 'attendances_students': ResourceConfig(tables.AttendancesStudents), 'classes_ts': ResourceConfig(tables.ClassesTs), 'notifications': ResourceConfig(tables.Notifications), 'student_guardians': ResourceConfig(tables.StudentGuardians), 'caches': ResourceConfig(tables.Caches), }).render() DOMAIN['modules']['schema']['image'].update({'type': 'media'}) DOMAIN['users']['schema']['photo'].update({'type': 'media'})
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from tables import Orders, Members # import os RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] MONGO_HOST = 'localhost' MONGO_PORT = 27017 MONGO_USERNAME = '' MONGO_PASSWORD = '' MONGO_DBNAME = 'apis' DEBUG = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:admin@localhost/apis' DOMAIN = DomainConfig({ 'orders': ResourceConfig(Orders), 'members': ResourceConfig(Members) }).render()
people_id = Column(Integer, ForeignKey('people.id')) # This will be the track the event utilizes tracks_id = Column(Integer, ForeignKey('people.id')) SETTINGS = { 'DEBUG': True, 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'DOMAIN': DomainConfig({ 'people': ResourceConfig(People), 'tracks': ResourceConfig(Tracks), 'events': ResourceConfig(Events) }).render() } app = Eve(auth=None, settings=SETTINGS, validator=ValidatorSQL, data=SQL) # bind SQLAlchemy db = app.data.driver Base.metadata.bind = db.engine db.Model = Base db.create_all() # Insert some example data in the db if not db.session.query(People).count(): db.session.add_all([
def Domain(): return DomainConfig(dict(contacts=ResourceConfig(Contacts)))
'DEBUG': True, 'SQLALCHEMY_DATABASE_URI': 'mysql://*****:*****@localhost/RZAPlatform', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'RESOURCE_METHODS': ['GET', 'POST'], 'DOMAIN': DomainConfig({ 'general': ResourceConfig(general), 'ammountOfGroup': ResourceConfig(ammountOfGroup), 'rooms': ResourceConfig(rooms), 'equipment': ResourceConfig(equipment), 'days': ResourceConfig(days), 'ranks': ResourceConfig(ranks), 'groups': ResourceConfig(groups), 'lessons': ResourceConfig(lessons), 'existanceOfEquipment': ResourceConfig(existanceOfEquipment), 'numberOfWeek': ResourceConfig(numberOfWeek), 'teachers': ResourceConfig(teachers), 'time': ResourceConfig(time), 'typesOfRooms': ResourceConfig(typesOfRooms), 'weeks': ResourceConfig(weeks), }).render() } # class TokenAuth(TokenAuth): # def check_auth(self, token, allowed_roles, resource, method): # """First we are verifying if the token is valid. Next # we are checking if user is authorized for given roles. # """ # login = User.verify_auth_token(token)
from eve_sqlalchemy.validation import ValidatorSQL from eve_sqlalchemy.config import DomainConfig, ResourceConfig from schema import Base, User import json import os def parse_field(resource, response): """Parse the JSON field, and convert keys to strings in case the user wants XML output.""" response['most_similar'] = { "most_similar_{}".format(k): v for k, v in json.loads(response['most_similar']).items() } settings = { 'SQLALCHEMY_DATABASE_URI': os.environ['USER_SIMILARITY_DB_URL'], 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'DOMAIN': DomainConfig({ 'user': ResourceConfig(User) }).render() } app = Eve(validator=ValidatorSQL, data=SQL, settings=settings) Base.metadata.bind = app.data.driver.engine app.data.driver.Model = Base app.on_fetched_item += parse_field if __name__ == '__main__': app.run(debug=True)
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from modelos.modelo import Pacientes DEBUG = True SQLALCHEMY_ECHO = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = 'postgres://postgres:@localhost:5432/criare' RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] DATE_FORMAT = "%d/%m/%Y %H:%M:%S" DOMAIN = DomainConfig({ 'pacientes': ResourceConfig(Pacientes), }).render()
_etag = Column(String(40)) class Node(BaseModel): __tablename__ = 'node' id = Column(Integer, primary_key=True) none_field = Column(Integer) SETTINGS = { 'SQLALCHEMY_DATABASE_URI': 'sqlite:///', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'RESOURCE_METHODS': ['GET', 'POST', 'DELETE'], 'ITEM_METHODS': ['GET', 'PATCH', 'DELETE', 'PUT'], 'DOMAIN': DomainConfig({ 'nodes': ResourceConfig(Node), }).render() } class TestGetNoneValues(TestMinimal): def setUp(self, url_converters=None): super(TestGetNoneValues, self).setUp(SETTINGS, url_converters, Base) def bulk_insert(self): self.app.data.insert('nodes', [{'id': k} for k in range(1, 5)]) def test_get_can_return_none_value(self): response, status = self.get('nodes/1') self.assert200(status) self.assertIn('none_field', response)
from eve_sqlalchemy.config import DomainConfig, ResourceConfig from eve_sqlalchemy.examples.many_to_one.domain import Child, Parent DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite://' SQLALCHEMY_TRACK_MODIFICATIONS = False RESOURCE_METHODS = ['GET', 'POST'] # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'parents': ResourceConfig(Parent), 'children': ResourceConfig(Child) }).render() DOMAIN['children']['datasource']['projection']['child_id'] = 1
# read-only access to the endpoint). RESOURCE_METHODS = ['GET', 'POST'] # Enable reads (GET), edits (PATCH) and deletes of individual items # (defaults to read-only item access). ITEM_METHODS = ['GET', 'PATCH', 'DELETE'] # The following two lines will output the SQL statements executed by # SQLAlchemy. This is useful while debugging and in development, but is turned # off by default. # -------- # SQLALCHEMY_ECHO = True # SQLALCHEMY_RECORD_QUERIES = True # The default schema is generated using DomainConfig: DOMAIN = DomainConfig({ 'hosts': ResourceConfig(Host), 'partnerships': ResourceConfig(Partnership), 'addresses': ResourceConfig(Address), 'appointments': ResourceConfig(Appointment), 'orders': ResourceConfig(Order) }).render() DOMAIN['addresses'].update({ 'item_title': 'address', 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'location_id' } })