def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. """ parser = self.create_parser(argv[0], argv[1]) options, args = parser.parse_args(argv[2:]) handle_default_options(options) try: self.execute(*args, **options.__dict__) except Exception as e: raise # self.stderr is not guaranteed to be set here stderr = getattr(self, 'stderr', OutputWrapper(sys.stderr, self.style.ERROR)) if options.traceback: stderr.write(traceback.format_exc()) else: stderr.write('%s: %s' % (e.__class__.__name__, e)) sys.exit(1) finally: orm = ORM.get() try: session = orm.sessionmaker() session.rollback() session.close() except: pass
def test_readonly_orm_creation(self): orm = ORM.get() session = orm.sessionmaker() result = session.execute('SELECT 1').fetchone() self.assertEqual(result, (1,)) session = orm.sessionmaker(readonly=True) result = session.execute('SELECT 1').fetchone() self.assertEqual(result, (1,))
def register(self, request, oauth_token, oauth_verifier, given_name, family_name, email): if hasattr(request, 'orm'): session = request.orm.sessionmaker() else: from baph.db.orm import ORM session = ORM.get().sessionmaker() request_token = request.session.pop(SESSION_KEY, None) if request_token and request_token.key == oauth_token: twitter = Twitter(request_token) access_token = twitter.get_access_token(oauth_verifier) if not access_token: return False profile = session.query(TwitterProfile) \ .filter_by(key=access_token.key, secret=access_token.secret) \ .first() if profile: user_obj = profile.user else: # Check that the username is unique, and if so, create a user # and profile twitter_user = twitter.user username = '******' % twitter_user.id user_ct = session.query(User) \ .filter_by(username=username) \ .count() if user_ct == 0: user_obj = User.create_user(username=username, email=email, password=None, session=session) user_obj.first_name = given_name user_obj.last_name = family_name profile = TwitterProfile(user=user_obj, uid=twitter_user.id, username=twitter.username, access_token=access_token) session.add(profile) session.commit() else: # Should we redirect here, or return False and redirect in # post_registration_redirect? return False signals.user_registered.send(sender=self.__class__, user=user_obj, request=request) user = authenticate(oauth_token=access_token.key, uid=twitter_user.id, session=session) login(request, user) elif request.user.is_authenticated(): user_obj = request.user else: # Perhaps we should handle this differently? user_obj = AnonymousUser() return user_obj
def register(self, request, **kwargs): if hasattr(request, 'orm'): session = request.orm.sessionmaker() else: from baph.db.orm import ORM session = ORM.get().sessionmaker() params = get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if params and 'uid' in params: uid = params['uid'] profile = session.query(FacebookProfile) \ .filter_by(uid=uid) \ .first() if profile: user_obj = profile.user else: # Check that the username is unique, and if so, create a user # and profile username = '******' % uid user_ct = session.query(User) \ .filter_by(username=username) \ .count() if user_ct == 0: fb = Facebook(params['access_token']) fb_user = fb.user user_obj = User.create_user(username=username, email=fb_user['email'], password=None, session=session) user_obj.first_name = fb_user['first_name'] user_obj.last_name = fb_user['last_name'] profile = FacebookProfile( user=user_obj, uid=uid, access_token=params['access_token'], expires_in=params['expires'], ) session.add(profile) session.commit() else: # Should we redirect here, or return False and redirect in # post_registration_redirect? return False signals.user_registered.send(sender=self.__class__, user=user_obj, request=request) user = authenticate(uid=uid, session=session) login(request, user) elif request.user.is_authenticated(): user_obj = request.user else: # Perhaps we should handle this differently? user_obj = AnonymousUser() return user_obj
def test_readonly_session_rollback(self): orm = ORM.get() session = orm.sessionmaker(readonly=True) sql = 'SELECT col FROM nonexistent_baph_table' try: result = session.execute(sql).fetchone() except SQLAlchemyError: orm.sessionmaker_rollback() result = session.execute('SELECT 1').fetchone() self.assertEqual(result, (1,))
def setUpClass(cls): super(RegistrationModelTests, cls).setUpClass() Site.__table__.create() User.__table__.create() orm = ORM.get() cls.session = orm.sessionmaker() cls.user_info['session'] = cls.session site = Site(id=settings.SITE_ID, domain='example.com', name=u'example.com') cls.session.add(site) cls.session.commit()
def key_to_value(obj, key, raw=False): """ Evaluate chained relations against a target object """ from baph.db.orm import ORM frags = key.split('.') if not raw: col_key = frags.pop() current_obj = obj while frags: if not current_obj: # we weren't able to follow the chain back, one of the # fks was probably optional, and had no value return None attr_name = frags.pop(0) previous_obj = current_obj previous_cls = type(previous_obj) current_obj = getattr(previous_obj, attr_name) if current_obj: # proceed to next step of the chain continue # relation was empty, we'll grab the fk and lookup the # object manually attr = getattr(previous_cls, attr_name) prop = attr.property related_cls = class_resolver(prop.argument) related_col = prop.local_remote_pairs[0][0] attr_ = column_to_attr(previous_cls, related_col) related_key = attr_.key related_val = getattr(previous_obj, related_key) if related_val is None: # relation and key are both empty: no parent found return None orm = ORM.get() session = orm.sessionmaker() current_obj = session.query(related_cls).get(related_val) if raw: return current_obj value = getattr(current_obj, col_key, None) if value: return str(value).strip() return None
def setUpClass(cls): ORM._database = None cls.orm = ORM.get() cls.session = cls.orm.sessionmaker() cls.session.execute('''\ CREATE TABLE test_baph_mapify ( id INTEGER PRIMARY KEY, string VARCHAR(16), number_with_decimal_point REAL(10) );''') cls.session.execute('''\ CREATE TABLE test_baph_mapify_join ( foreign_key INTEGER PRIMARY KEY REFERENCES test_baph_mapify(id), other_string VARCHAR(16) );''')
def facebook_login(request): if hasattr(request, 'orm'): session = request.orm.sessionmaker() else: from baph.db.orm import ORM session = ORM.get().sessionmaker() params = get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if params: user = authenticate(uid=params['uid'], session=session) if user is not None: if user.is_active: login(request, user) return redirect(settings.LOGIN_REDIRECT_URL, {}, ()) else: # Disabled account, redirect and notify? return redirect('/', {}, ()) else: # Invalid user, redirect and notify? return redirect('/', {}, ()) elif request.user.is_authenticated(): return redirect(settings.LOGIN_REDIRECT_URL, {}, ()) else: return redirect('/account/register/', {}, ())
def setUpClass(cls): cls.orm = ORM.get()
def test_orm_creation(self): orm = ORM.get() session = orm.sessionmaker() result = session.execute('SELECT 1').fetchone() self.assertEqual(result, (1, ))
def test_readonly_session_remove(self): # Please fix...this is not very useful IMO. -Mark orm = ORM.get() session = orm.sessionmaker(readonly=True) session.execute('SELECT 1') orm.sessionmaker_remove()
def test_create_url(self): # URLs taken from: http://www.sqlalchemy.org/docs/05/dbengine.html test_data = [ { 'expected': 'postgres://*****:*****@localhost/mydatabase', 'params': { 'ENGINE': 'postgres', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', 'NAME': 'mydatabase', }, }, { 'expected': 'postgres://scott@localhost/mydatabase', 'params': { 'ENGINE': 'postgres', 'USER': '******', 'HOST': 'localhost', 'NAME': 'mydatabase', }, }, { 'expected': 'postgres://scott@localhost/mydatabase', 'params': { 'ENGINE': 'postgres', 'USER': '******', 'PASSWORD': '', 'HOST': 'localhost', 'NAME': 'mydatabase', }, }, { 'expected': 'oracle://*****:*****@tnsname', 'params': { 'ENGINE': 'oracle', 'USER': '******', 'PASSWORD': '******', 'HOST': 'tnsname', }, }, { 'expected': 'mssql://mydsn', 'params': { 'ENGINE': 'mssql', 'HOST': 'mydsn', }, }, { 'expected': 'sqlite:///foo.db', 'params': { 'ENGINE': 'sqlite', 'NAME': 'foo.db', }, }, { 'expected': 'sqlite:////absolute/path/to/foo.db', 'params': { 'ENGINE': 'sqlite', 'NAME': '/absolute/path/to/foo.db', }, }, { 'expected': 'sqlite:////absolute/path/to/foo.db', 'params': { 'ENGINE': 'sqlite', 'USER': '', 'PASSWORD': '', 'HOST': '', 'NAME': '/absolute/path/to/foo.db', }, }, { 'expected': 'sqlite://', 'params': { 'ENGINE': 'sqlite', }, }, ] for data in test_data: self.assertEqual(ORM._create_url(data['params']), data['expected'])
def test_session_close(self): # Please fix...this is not very useful IMO. -Mark orm = ORM.get() session = orm.sessionmaker() session.execute('SELECT 1') orm.sessionmaker_close()
def loaddata(self, fixture_labels): #connection = connections[self.using] connection = orm = ORM.get(self.using) # Keep a count of the installed objects and fixtures self.fixture_count = 0 self.loaded_object_count = 0 self.fixture_object_count = 0 self.models = set() self.serialization_formats = serializers.get_public_serializer_formats() # Forcing binary mode may be revisited after dropping Python 2 support (see #22399) self.compression_formats = { None: (open, 'rb'), 'gz': (gzip.GzipFile, 'rb'), 'zip': (SingleZipReader, 'r'), } if has_bz2: self.compression_formats['bz2'] = (bz2.BZ2File, 'r') ''' with connection.constraint_checks_disabled(): for fixture_label in fixture_labels: self.load_label(fixture_label) ''' session = orm.sessionmaker() session.close() for fixture_label in fixture_labels: self.load_label(fixture_label) session.commit() # Since we disabled constraint checks, we must manually check for # any invalid keys that might have been added # TODO: implement this ''' table_names = [model._meta.db_table for model in self.models] try: connection.check_constraints(table_names=table_names) except Exception as e: e.args = ("Problem installing fixtures: %s" % e,) raise ''' # If we found even one object in a fixture, we need to reset the # database sequences. # TODO: implement this ''' if self.loaded_object_count > 0: sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models) if sequence_sql: if self.verbosity >= 2: self.stdout.write("Resetting sequences\n") cursor = connection.cursor() for line in sequence_sql: cursor.execute(line) cursor.close() ''' if self.fixture_count == 0 and self.hide_empty: pass elif self.fixture_object_count == self.loaded_object_count: logger.info("Installed %d object(s) from %d fixture(s)" % (self.loaded_object_count, self.fixture_count)) else: logger.info("Installed %d object(s) (of %d) from %d fixture(s)" % (self.loaded_object_count, self.fixture_object_count, self.fixture_count))
def process_request(self, request): request.orm = ORM.get()
# -*- coding: utf-8 -*- from baph.db.models import Model from baph.db.orm import ORM from baph.auth.models import User, AUTH_USER_FIELD from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relation orm = ORM.get() class FacebookProfile(orm.Base, Model): '''Facebook Connect-related information for a user.''' __tablename__ = 'auth_facebook_profile' user_id = Column(AUTH_USER_FIELD, ForeignKey(User.id), primary_key=True) uid = Column(String(255), nullable=False, unique=True) access_token = Column(String(100), nullable=True) expires_in = Column(Integer, default=0, nullable=False) user = relation(User, lazy=False)
def handle_noargs(self, **options): verbosity = 1 #int(options.get('verbosity')) interactive = options.get('interactive') show_traceback = options.get('traceback') self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith('No module named') or 'management' not in msg: raise db = options.get('database') orm = ORM.get(db) db_info = orm.settings_dict is_test_db = db_info.get('TEST', False) if not is_test_db: print 'Database "%s" cannot be purged because it is not a test ' \ 'database.\nTo flag this as a test database, set TEST to ' \ 'True in the database settings.' % db sys.exit() if interactive: confirm = raw_input('\nYou have requested a purge of database ' \ '"%s" (%s). This will IRREVERSIBLY DESTROY all data ' \ 'currently in the database, and DELETE ALL TABLES AND ' \ 'SCHEMAS. Are you sure you want to do this?\n\n' \ 'Type "yes" to continue, or "no" to cancel: ' \ % (db, orm.engine.url)) else: confirm = 'yes' if confirm == 'yes': # get a list of all schemas used by the app default_schema = orm.engine.url.database app_schemas = set(orm.Base.metadata._schemas) app_schemas.add(default_schema) url = deepcopy(orm.engine.url) url.database = None engine = create_engine(url) inspector = inspect(engine) # get a list of existing schemas db_schemas = set(inspector.get_schema_names()) schemas = app_schemas.intersection(db_schemas) app_tables = set() for table in orm.Base.metadata.tables.values(): schema = table.schema or default_schema app_tables.add('%s.%s' % (schema, table.name)) metadata = MetaData() db_tables = [] all_fks = [] for schema in schemas: for table_name in inspector.get_table_names(schema): fullname = '%s.%s' % (schema, table_name) if fullname not in app_tables: continue fks = [] for fk in inspector.get_foreign_keys(table_name, schema=schema): if not fk['name']: continue fks.append(ForeignKeyConstraint((),(),name=fk['name'])) t = Table(table_name, metadata, *fks, schema=schema) db_tables.append(t) all_fks.extend(fks) session = Session(bind=engine) for fkc in all_fks: session.execute(DropConstraint(fkc)) for table in db_tables: session.execute(DropTable(table)) for schema in schemas: session.execute(DropSchema(schema)) session.commit() session.bind.dispose() else: self.stdout.write("Purge cancelled.\n")
def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) interactive = options.get('interactive') show_traceback = options.get('traceback') load_initial_data = options.get('load_initial_data') self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith( 'No module named') or 'management' not in msg: raise db = options.get('database') orm = ORM.get(db) engine = orm.engine default_schema = engine.url.database # the default db may not exist yet, so we remove it before connecting engine.url.database = None frags = str(engine.url).split('?') tmp_url = frags[0] if len(frags) == 2: if not tmp_url.endswith('/'): # query strings will break this if it doesn't end with a / tmp_url += '/' tmp_url += '?%s' % frags[1] engine.url.database = default_schema tmp_engine = create_engine(tmp_url) tmp_conn = tmp_engine.connect() existing_schemas = set( [s[0] for s in tmp_conn.execute('show databases')]) if not default_schema in existing_schemas: tmp_engine.execute(CreateSchema(default_schema)) existing_schemas.add(default_schema) orm = ORM.get(db) # now reconnect with the default_db provided conn = engine.connect() Base.metadata.bind = engine if verbosity >= 3: self.stdout.write("Getting existing schemas...\n") for schema in existing_schemas: self.stdout.write("\t%s\n" % schema) else: self.stdout.write("\tNone\n") existing_tables = [] if verbosity >= 1: self.stdout.write("Getting existing tables...\n") for schema in existing_schemas: for name in engine.engine.table_names(schema, connection=conn): existing_tables.append('%s.%s' % (schema, name)) if verbosity >= 3: self.stdout.write("\t%s.%s\n" % (schema, name)) existing_models = [] if verbosity >= 1: self.stdout.write("Getting existing models...\n") for cls_name, cls in Base._decl_class_registry.items(): tablename = get_tablename(cls) if tablename and tablename in existing_tables: existing_models.append(cls) if verbosity >= 3: self.stdout.write("\t%s\n" % cls) all_tables = [] if verbosity >= 1: self.stdout.write("Getting required tables...\n") for table in Base.metadata.sorted_tables: tablename = get_tablename(table) all_tables.append(tablename) if verbosity >= 3: self.stdout.write("\t%s\n" % tablename) all_models = [] if verbosity >= 1: self.stdout.write("Getting required models...\n") for app in get_apps(): for model in get_models(app, include_auto_created=True): app_name = app.__name__.rsplit('.', 1)[0] all_models.append((app_name, model)) if verbosity >= 3: self.stdout.write("\t%s.%s\n" % (app_name, model)) schema_manifest = set() table_manifest = set() if verbosity >= 1: self.stdout.write('Building manifest...\n') for app_name, model in all_models: tablename = get_tablename(model) if tablename in existing_tables: continue table_manifest.add((app_name, model)) schema = tablename.rsplit('.', 1)[0] if schema not in existing_schemas: schema_manifest.add(schema) table_manifest = sorted( table_manifest, key=lambda x: all_tables.index(get_tablename(x[1]))) if verbosity >= 3: print 'Schema Manifest:\n' for schema in schema_manifest: print '\t%s\n' % schema print 'Model/Table Manifest\n' for app_name, model in table_manifest: print '\t%s.%s (%s)\n' % (app_name, model._meta.object_name, get_tablename(model)) # create any missing schemas if verbosity >= 1: self.stdout.write("Creating schemas ...\n") for schema in schema_manifest: if verbosity >= 3: self.stdout.write("\t%s\n" % schema) engine.execute(CreateSchema(schema)) existing_schemas.add(schema) # create any missing tables created_models = set() to_create = [] if verbosity >= 1: self.stdout.write("Creating tables ...\n") for app_name, model in table_manifest: if verbosity >= 3: self.stdout.write("\tCreating table for model %s.%s\n" % (app_name, model._meta.object_name)) tablename = get_tablename(model) if tablename not in existing_tables: table = model.__table__ to_create.append(table) existing_tables.append(tablename) existing_models.append(model) created_models.add(model) orm.Base.metadata.create_all(bind=engine, tables=to_create) # Send the post_syncdb signal emit_post_sync_signal(created_models, verbosity, interactive, db) # Load initial_data fixtures (unless that has been disabled) if load_initial_data: call_command('loaddata', 'initial_data', verbosity=verbosity, database=db, skip_validation=True)
def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) interactive = options.get('interactive') show_traceback = options.get('traceback') load_initial_data = options.get('load_initial_data') self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError as exc: # This is slightly hackish. We want to ignore ImportErrors # if the "management" module itself is missing -- but we don't # want to ignore the exception if the management module exists # but raises an ImportError for some reason. The only way we # can do this is to check the text of the exception. Note that # we're a bit broad in how we check the text, because different # Python implementations may not use the same text. # CPython uses the text "No module named management" # PyPy uses "No module named myproject.myapp.management" msg = exc.args[0] if not msg.startswith('No module named') or 'management' not in msg: raise db = options.get('database') orm = ORM.get(db) engine = orm.engine default_schema = engine.url.database # the default db may not exist yet, so we remove it before connecting engine.url.database = None frags = str(engine.url).split('?') tmp_url = frags[0] if len(frags) == 2: if not tmp_url.endswith('/'): # query strings will break this if it doesn't end with a / tmp_url += '/' tmp_url += '?%s' % frags[1] engine.url.database = default_schema tmp_engine = create_engine(tmp_url) tmp_conn = tmp_engine.connect() existing_schemas = set([s[0] for s in tmp_conn.execute('show databases')]) if not default_schema in existing_schemas: tmp_engine.execute(CreateSchema(default_schema)) existing_schemas.add(default_schema) orm = ORM.get(db) # now reconnect with the default_db provided conn = engine.connect() Base.metadata.bind = engine if verbosity >= 3: self.stdout.write("Getting existing schemas...\n") for schema in existing_schemas: self.stdout.write("\t%s\n" % schema) else: self.stdout.write("\tNone\n") existing_tables = [] if verbosity >= 1: self.stdout.write("Getting existing tables...\n") for schema in existing_schemas: for name in engine.engine.table_names(schema, connection=conn): existing_tables.append('%s.%s' % (schema,name)) if verbosity >= 3: self.stdout.write("\t%s.%s\n" % (schema,name)) existing_models = [] if verbosity >= 1: self.stdout.write("Getting existing models...\n") for cls_name, cls in Base._decl_class_registry.items(): tablename = get_tablename(cls) if tablename and tablename in existing_tables: existing_models.append(cls) if verbosity >= 3: self.stdout.write("\t%s\n" % cls) all_tables = [] if verbosity >= 1: self.stdout.write("Getting required tables...\n") for table in Base.metadata.sorted_tables: tablename = get_tablename(table) all_tables.append(tablename) if verbosity >= 3: self.stdout.write("\t%s\n" % tablename) all_models = [] if verbosity >= 1: self.stdout.write("Getting required models...\n") for app in get_apps(): for model in get_models(app, include_auto_created=True): app_name = app.__name__.rsplit('.',1)[0] all_models.append( (app_name, model) ) if verbosity >= 3: self.stdout.write("\t%s.%s\n" % (app_name,model)) schema_manifest = set() table_manifest = set() if verbosity >= 1: self.stdout.write('Building manifest...\n') for app_name, model in all_models: tablename = get_tablename(model) if tablename in existing_tables: continue table_manifest.add( (app_name, model) ) schema = tablename.rsplit('.',1)[0] if schema not in existing_schemas: schema_manifest.add(schema) table_manifest = sorted(table_manifest, key=lambda x: all_tables.index(get_tablename(x[1]))) if verbosity >= 3: print 'Schema Manifest:\n' for schema in schema_manifest: print '\t%s\n' % schema print 'Model/Table Manifest\n' for app_name, model in table_manifest: print '\t%s.%s (%s)\n' % (app_name, model._meta.object_name, get_tablename(model)) # create any missing schemas if verbosity >= 1: self.stdout.write("Creating schemas ...\n") for schema in schema_manifest: if verbosity >= 3: self.stdout.write("\t%s\n" % schema) engine.execute(CreateSchema(schema)) existing_schemas.add(schema) # create any missing tables created_models = set() to_create = [] if verbosity >= 1: self.stdout.write("Creating tables ...\n") for app_name, model in table_manifest: if verbosity >= 3: self.stdout.write("\tCreating table for model %s.%s\n" % (app_name, model._meta.object_name)) tablename = get_tablename(model) if tablename not in existing_tables: table = model.__table__ to_create.append(table) existing_tables.append(tablename) existing_models.append(model) created_models.add(model) orm.Base.metadata.create_all(bind=engine, tables=to_create) # Send the post_syncdb signal emit_post_sync_signal(created_models, verbosity, interactive, db) # Load initial_data fixtures (unless that has been disabled) if load_initial_data: call_command('loaddata', 'initial_data', verbosity=verbosity, database=db, skip_validation=True)
def setUpClass(cls): super(RegistrationViewTests, cls).setUpClass() User.__table__.create() orm = ORM.get() cls.session = orm.sessionmaker()
def setUpClass(cls): super(RegistrationFormTests, cls).setUpClass() User.__table__.create() orm = ORM.get() cls.session = orm.sessionmaker()
from hashlib import sha1 as sha_constructor import random from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from sqlalchemy.orm import joinedload from baph.auth.models import User, Organization from baph.auth.registration import settings from baph.auth.registration.managers import SignupManager from baph.auth.utils import generate_sha1 from baph.db.orm import ORM orm = ORM.get() attrs_dict = {'class': 'required'} def identification_field_factory(label, error_required): """ A simple identification field factory which enable you to set the label. :param label: String containing the label for this field. :param error_required: String containing the error message if the field is left empty. """