def setUp(self): super(TestPolymorphy, self).setUp() self._related_resource_configs = { Node: ('nodes', ResourceConfig(Node)), Thing: ('things', ResourceConfig(Thing)), Group: ('groups', ResourceConfig(Group)), }
def setUp(self): super(TestAmbiguousRelations, self).setUp() self._domain = DomainConfig({ 'users': ResourceConfig(User), 'admins': ResourceConfig(User), 'groups': ResourceConfig(Group) })
def _render(self, model_or_resource_config): if hasattr(model_or_resource_config, 'render'): rc = model_or_resource_config else: rc = ResourceConfig(model_or_resource_config) return rc.render(self._created, self._updated, self._etag, self._related_resource_configs)
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)
def test_fail_without_user_specified_id_field(self): model = MultiColumnPrimaryKey with self.assertRaises(ConfigException) as cm: ResourceConfig(model) self.assertIn( "{}'s primary key consists of zero or multiple columns, " "thus we cannot deduce which one to use.".format(model.__name__), str(cm.exception))
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 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
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])
# This will be the creator of the event itself 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():
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'] })
MAIL_DEFAULT_SENDER = ('no-reply', '*****@*****.**') # MAIL_MAX_EMAILS : default None # MAIL_SUPPRESS_SEND : default app.testing # MAIL_ASCII_ATTACHMENTS : default False # 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({ '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':
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
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()
def test_fail_for_non_existent_user_specified_id_field(self, model): with self.assertRaises(ConfigException) as cm: ResourceConfig(model, id_field='foo') self.assertIn('{}.foo does not exist.'.format(model.__name__), str(cm.exception))
_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)
typesOfRooms = Base.classes.t_type_aud weeks = Base.classes.t_week print("Hi") SETTINGS = { '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() }
InternalTransactions, Invoices, Login, Payments, Products, ) SQLALCHEMY_DATABASE_URI = 'sqlite:///' # %s' % db_filename SQLALCHEMY_TRACK_MODIFICATIONS = False 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),
def test_fail_with_user_specified_id_field_as_subset_of_primary_key(self): model = MultiColumnPrimaryKey with self.assertRaises(ConfigException) as cm: ResourceConfig(model, id_field='id_1') self.assertIn('{}.id_1 is not unique.'.format(model.__name__), str(cm.exception))
def setUp(self): super(TestManyToOneRelationship, self).setUp() self._related_resource_configs = { Child: ('children', ResourceConfig(Child)) }
def test_set_to_primary_key_by_user(self): rc = ResourceConfig(SingleColumnPrimaryKey, id_field='id') self.assertEqual(rc.id_field, 'id')
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'
def setUp(self): super(TestForeignPrimaryKey, self).setUp() self._related_resource_configs = { Node: ('nodes', ResourceConfig(Node)), Lock: ('locks', ResourceConfig(Lock)) }
def setUp(self): super(TestOneToOneRelationship, self).setUp() self._related_resource_configs = { Child: ('children', ResourceConfig(Child)), Parent: ('parents', ResourceConfig(Parent)) }
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()
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()
# Allowed methods RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', '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: # 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),
def test_fail_for_non_unique_user_specified_id_field(self, model): with self.assertRaises(ConfigException) as cm: ResourceConfig(model, id_field='non_unique') self.assertIn('{}.non_unique is not unique.'.format(model.__name__), str(cm.exception))
def setUp(self): super(TestAssociationProxy, self).setUp() self._related_resource_configs = { User: ('users', ResourceConfig(User)), Keyword: ('keywords', ResourceConfig(Keyword)) }
}, '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