def _allocate_specified_segment(self, session, seg_id, source):
try:<EOL><INDENT>with session.begin(subtransactions=True):<EOL><INDENT>alloc = (session.query(self.model).filter_by(<EOL>segmentation_id=seg_id).first())<EOL>if alloc:<EOL><INDENT>if alloc.allocated:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>count = (session.query(self.model).<EOL>filter_by(allocated=False,<EOL>segmentation_id=seg_id).update(<EOL>{"<STR_LIT>": True}))<EOL>if count:<EOL><INDENT>return alloc<EOL><DEDENT><DEDENT><DEDENT>alloc = self.model(segmentation_id=seg_id,<EOL>allocated=True, source=source)<EOL>session.add(alloc)<EOL><DEDENT><DEDENT>except db_exc.DBDuplicateEntry:<EOL><INDENT>alloc = None<EOL><DEDENT>return alloc<EOL>
Allocate specified segment.

        If segment exists, then try to allocate it and return db object
        If segment does not exists, then try to create it and return db object
        If allocation/creation failed (duplicates), then return None