class Route(Resource): add_args = { 'frm': fields.String(required=True), 'to': fields.String(required=True), } @use_kwargs(add_args) def get(self, frm, to): # page = Page.query.filter_by(slug=slug).first() # if not page: # abort(404, message="Page {} doesn't exist".format(slug)) # return page # r = { # "content": "ndull", # "id": 0, # "slug": "ndull", # "title": "ndull" # } routes = get_safe_routes_raw(frm, to) return routes #return jsonify(r) @use_kwargs(add_args) def post(self, frm, to): routes = get_safe_routes_raw(frm, to) return routes
class AlbumFields(Fieldset): id = fields.Integer(attribute="a_id"), title = fields.String, thumbnail = OptionalNestedField(PictureFields, "id", plain_field=fields.Integer) date = fields.String(attribute="a_date"), location_name = fields.String(attribute='a_location'), description = fields.String(attribute='a_desc')
class EventLocationFields(Fieldset): id = fields.Integer(attribute="lid") name = fields.String(attribute="location") url = fields.String slug = fields.String(attribute="location_url") street = fields.String(attribute="strasse") zip_no = fields.String(attribute="plz") town = fields.String(attribute="stadt")
def marshal_deposition(cls, deposition): """ Generate a JSON representation for REST API of a Deposition """ # Get draft if deposition.has_sip() and '_edit' in deposition.drafts: draft = deposition.get_draft('_edit') metadata_fields = cls.marshal_metadata_edit_fields elif deposition.has_sip(): # FIXME: Not based on latest available data in record. sip = deposition.get_latest_sip(sealed=True) draft = record_to_draft( Record.create(sip.package, master_format='marc'), post_process=process_draft ) metadata_fields = cls.marshal_metadata_edit_fields else: draft = deposition.get_or_create_draft('_metadata') metadata_fields = cls.marshal_metadata_fields # Fix known differences in marshalling current_app.logger.debug(draft.values) draft.values = filter_empty_elements(draft.values) current_app.logger.debug(draft.values) # Set disabled values to None in output for field, flags in draft.flags.items(): if 'disabled' in flags and field in draft.values: current_app.logger.debug(field) del draft.values[field] # Marshal deposition obj = marshal(deposition, cls.marshal_deposition_fields) # Marshal the metadata attribute obj['metadata'] = marshal(unicodifier(draft.values), metadata_fields) # Add record and DOI information from latest SIP for sip in deposition.sips: if sip.is_sealed(): recjson = sip.metadata if recjson.get('recid'): obj['record_id'] = fields.Integer().format( recjson.get('recid') ) obj['record_url'] = fields.String().format(url_for( 'record.metadata', recid=recjson.get('recid'), _external=True )) if (recjson.get('doi') and recjson.get('doi').startswith( cfg['CFG_DATACITE_DOI_PREFIX'] + "/")): obj['doi'] = fields.String().format(recjson.get('doi')) obj['doi_url'] = fields.String().format( "http://dx.doi.org/%s" % obj['doi'] ) break return obj
def get_resource_fields(self): return { 'id': fields.Integer(attribute='pk'), 'name': fields.String, 'slug': fields.String, 'uri': InstanceURI('artist'), 'image': fields.String(default=app.config['DEFAULT_ARTIST_IMAGE']), 'events_uri': fields.String(attribute='events'), }
class MessageFields(Fieldset): id = fields.Integer(attribute="mt_id") title = fields.String(attribute='mt_title') date = fields.Integer(attribute="mt_date") from_name = ObjectMemberField(member="name", attribute="from_user") to_name = ObjectMemberField(member="name", attribute="to_user") folder = fields.String(attribute="mt_vid_folder") body = OptionalNestedField(BodyFields, "msg_id", plain_field=fields.Integer)
def get_resource_fields(self): return { 'id': fields.String(attribute='pk'), 'name': fields.String, 'slug': fields.String, 'year': fields.Integer, 'uri': InstanceURI('albums'), 'artists': ManyToManyField(Artist, { 'id': fields.String(attribute='pk'), 'uri': InstanceURI('artists'), }), 'cover': fields.String(default=app.config['DEFAULT_ALBUM_COVER']), }
class oxtrustNode(BaseModel): # Swager Doc resource_fields = { "id": fields.String(attribute="Node unique identifier"), "name": fields.String(attribute="Node name"), "type": fields.String(attribute="Node type"), "ip": fields.String(attribute="Node IP address"), "cluster_id": fields.String(attribute="Cluster ID"), } def __init__(self): self.id = "" self.cluster_id = "" self.name = "" self.hostname = "" self.ip = "" self.type = "oxtrust" self.tomcat_home = "/opt/tomcat" self.tomcat_conf_dir = "/opt/tomcat/conf" self.tomcat_log_folder = "/opt/tomcat/logs" self.ldap_binddn = 'cn=directory manager' self.openssl_cmd = "/usr/bin/openssl" self.cert_folder = "/etc/certs" self.httpd_key = "/etc/certs/httpd.key" self.httpd_key_orig = "/etc/certs/httpd.key.orig" self.httpd_csr = "/etc/certs/httpd.csr" self.httpd_crt = "/etc/certs/httpd.crt" self.defaultTrustStoreFN = '/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security/cacerts' self.shib_jks_pass = "" self.encoded_shib_jks_pw = "" self.shib_jks_fn = "/etc/certs/shibIDP.jks" # enabled if we have saml self.oxtrust_config_generation = "disabled" # these templates should be rendered and copied to tomcat # conf directory self.oxtrust_properties = "api/templates/salt/oxtrust/oxTrust.properties" self.oxtrust_ldap_properties = "api/templates/salt/oxtrust/oxTrustLdap.properties" self.oxtrust_log_rotation_configuration = "api/templates/salt/oxtrust/oxTrustLogRotationConfiguration.xml" self.oxauth_static_conf_json = "api/templates/salt/_shared/oxauth-static-conf.json" # the following template should be rendered and copied # to apache2 conf directory self.apache2_ssl_conf = "api/templates/salt/_shared/https_gluu.conf" # the following template should be copied to # /opt/tomcat/conf/template/conf self.oxtrust_cache_refresh_properties = "api/templates/salt/oxtrust/oxTrustCacheRefresh-template.properties.vm"
class AuthToken(UserBase): add_args = { 'email': fields.String(required=True), 'uid': fields.String(required=True), } @use_kwargs(add_args) def post(self): args = self.token_parser.parse_args() user = self.get_user(email) if user.check_password(uid): token = user.generate_auth_token() return {'token': token.decode('ascii')}, 200 else: abort(401, message="Invalid login info")
class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) created_at = db.Column(db.DateTime()) confirmed_at = db.Column(db.DateTime()) playlists = db.relationship('Playlist', backref='user', lazy='dynamic') def is_authenticated(self): return True def is_active(self): return self.active def is_anonymous(self): return False def get_id(self): return self.id def update_password(self, password): self.password = bcrypt.encrypt(password) def check_password(self, password): return bcrypt.verify(password, self.password) resource_fields = {'id': fields.Integer(), 'name': fields.String()}
def get_resource_fields(self): return { 'id': fields.String(attribute='pk'), 'name': fields.String, 'user': ForeignKeyField(User, { 'id': fields.String(attribute='pk'), 'uri': InstanceURI('users'), }), 'read_only': fields.Boolean, 'creation_date': fields.DateTime, 'length': fields.Integer, 'tracks': PlaylistField({ 'id': fields.String(attribute='pk'), 'uri': InstanceURI('tracks'), }), }
class TodoItemWithResourceFields: """This is an example of how Output Fields work (http://flask-restful.readthedocs.org/en/latest/fields.html). Output Fields lets you add resource_fields to your model in which you specify the output of the model when it gets sent as an HTTP response. flask-restful-swagger takes advantage of this to specify the fields in the model""" resource_fields = { 'a_string': fields.String(attribute='a_string_field_name'), 'a_formatted_string': fields.FormattedString, 'an_int': fields.Integer, 'a_bool': fields.Boolean, 'a_url': fields.Url, 'a_float': fields.Float, 'an_float_with_arbitrary_precision': fields.Arbitrary, 'a_fixed_point_decimal': fields.Fixed, 'a_datetime': fields.DateTime, 'a_list_of_strings': fields.List(fields.String), 'a_nested_attribute': fields.Nested(ModelWithResourceFields.resource_fields), 'a_list_of_nested_types': fields.List(fields.Nested(ModelWithResourceFields.resource_fields)), }
class Register(UserBase): add_args = { 'email': fields.String(required=True), 'uid': fields.String(required=True), } @use_kwargs(add_args) def post(self, email, uid): # todo store and verify uid user = User.query.filter_by(username=email).first() if not user: user = User(username=email) user.set_password(uid) db.session.add(user) db.session.commit() token = user.generate_auth_token() return {'token': token.decode('ascii')}, 200
class oxauthNode(BaseModel): # Swager Doc resource_fields = { "id": fields.String(attribute="Node unique identifier"), "name": fields.String(attribute="Node name"), "type": fields.String(attribute="Node type"), "ip": fields.String(attribute="Node IP address"), "cluster_id": fields.String(attribute="Cluster ID"), } def __init__(self): self.id = "" self.cluster_id = "" self.name = "" self.ip = "" self.type = "oxauth" self.defaultTrustStoreFN = '/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security/cacerts' self.ldap_binddn = 'cn=directory manager' self.tomcat_home = "/opt/tomcat" self.tomcat_conf_dir = "/opt/tomcat/conf" self.openssl_cmd = "/usr/bin/openssl" self.cert_folder = "/etc/certs" self.httpd_key = "/etc/certs/httpd.key" self.httpd_key_orig = "/etc/certs/httpd.key.orig" self.httpd_csr = "/etc/certs/httpd.csr" self.httpd_crt = "/etc/certs/httpd.crt" self.oxauth_lib = "/opt/tomcat/webapps/oxauth/WEB-INF/lib" # the following template should be copied to tomcat conf directory self.oxauth_errors_json = "api/templates/salt/oxauth/oxauth-errors.json" # the following templates should be rendered and copied # to tomcat conf directory self.oxauth_ldap_properties = "api/templates/salt/oxauth/oxauth-ldap.properties" self.oxauth_config_xml = "api/templates/salt/oxauth/oxauth-config.xml" self.oxauth_static_conf_json = "api/templates/salt/_shared/oxauth-static-conf.json" self.tomcat_server_xml = "api/templates/salt/oxauth/server.xml" # the following template should be rendered and copied # to apache2 conf directory self.apache2_ssl_conf = "api/templates/salt/_shared/https_gluu.conf"
class PlaylistElement(db.Model): id = db.Column(db.Integer, primary_key=True) youtube_id = db.Column(db.String(255)) title = db.Column(db.String(255)) thumbnail = db.Column(db.String(255)) added_at = db.Column(db.DateTime()) added_by_id = db.Column(db.Integer, db.ForeignKey('user.id')) added_by = db.relationship('User') playlist_id = db.Column(db.Integer, db.ForeignKey('playlist.id')) resource_fields = { 'id': fields.String(), 'youtube_id': fields.String(), 'title': fields.String(), 'thumbnail': fields.String(), 'added_at': fields.DateTime(), 'added_by': fields.Nested(User.resource_fields) }
class HistoryStore(Resource): add_args = { 'src_lat': fields.String(required=True), 'src_long': fields.String(required=True), 'dest_lat': fields.String(required=True), 'dest_long': fields.String(required=True), 'user_id': fields.String(required=True) } #def post(self, src_lat, src_long, dest_lat, dest_long, user_id): @use_kwargs(add_args) def post(self, src_lat, src_long, dest_lat, dest_long, user_id): # todo store and verify uid record = History(src_lat, src_long, dest_lat, dest_long, user_id) db.session.add(record) db.session.commit() return record.id
class BlueprintValidationStatus(object): resource_fields = { 'blueprintId': fields.String(attribute='blueprint_id'), 'status': fields.String } def __init__(self, **kwargs): self.blueprint_id = kwargs['blueprint_id'] self.status = kwargs['status']
def get_resource_fields(self): return { 'id': fields.String(attribute='pk'), 'uri': InstanceURI('tracks'), 'files': TrackFiles, 'bitrate': fields.Integer, 'length': fields.Integer, 'title': fields.String, 'slug': fields.String, 'artists': ManyToManyField(Artist, { 'id': fields.String(attribute='pk'), 'uri': InstanceURI('artists'), }), 'albums': ManyToManyField(Album, { 'id': fields.String(attribute='pk'), 'uri': InstanceURI('albums'), }), 'ordinal': fields.Integer, }
def get_resource_fields(self): return { 'id': fields.Integer(attribute='pk'), 'uri': InstanceURI('lyrics'), 'text': fields.String, 'source_uri': fields.String(attribute='source'), 'track': ForeignKeyField(Track, { 'id': fields.Integer(attribute='pk'), 'uri': InstanceURI('track'), }), }
class Playlist(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) slug = db.Column(db.String(255)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) last_updated = db.Column(db.DateTime()) elements = db.relationship('PlaylistElement', backref='playlist', lazy='dynamic') def update_slug(self): self.slug = slugify(self.name) resource_fields = { 'id': fields.String(), 'name': fields.String(), 'slug': fields.String(), 'user': fields.Nested(User.resource_fields), 'elements': fields.List(fields.Nested(PlaylistElement.resource_fields)), 'last_updated': fields.DateTime() }
class Default(Challenge): """The default challenge class""" # the allowed actions for this challenge type, and whether they # represent the task being available or not def actions(): return { 'created': True, 'available': True, 'skipped': True, 'assigned': False, 'falsepositive': False, 'fixed': False, 'deleted': False } done_dialog_text = "This area is being loaded in your editor. \ Did you fix it?" # an empty string will trigger the default buttons. done_dialog_buttons = "" marshal_fields = { 'slug': fields.String, 'title': fields.String, 'description': fields.String, 'blurb': fields.String, 'help': fields.String, 'instruction': fields.String, 'active': fields.Boolean, 'difficulty': fields.Integer } marshal_fields['done_dlg'] = {} marshal_fields['done_dlg']['text'] = fields.String( attribute='done_dialog_text') marshal_fields['done_dlg']['buttons'] = fields.String( attribute='done_dialog_buttons')
class PushToken(UserBase): add_args = { 'push_token': fields.String(required=True), } @use_kwargs(add_args) @login_required def post(self, push_token): user = g.user try: user.set_push_token(push_token) db.session.add(user) db.session.commit() return "success", 200 except: return "err", 400
class EventFields(Fieldset): class Meta: default_embedd = [] id = fields.Integer(attribute="event_id") title = fields.String start = fields.DateTime end = fields.DateTime editable = fields.Boolean allDay = fields.Boolean type = fields.String(attribute="type_name") overall_end = fields.DateTime category = OptionalNestedField(EventCategoryFields, "tag", attribute="category_instance") location = OptionalNestedField(EventLocationFields, "lid", attribute="location")
from flask import request from flask.ext.restful import Resource, fields, abort from webargs.flaskparser import use_kwargs, parser from models import Categories from resources.paginator import Paginator categories_fields = { 'id': fields.Integer, 'title': fields.String(255), 'lang': fields.String(10) } @parser.error_handler def handle_request_parsing_error(err): abort(422, errors=err.messages) class CategoriesResources(Resource, Paginator): @use_kwargs(Paginator.args) def get(self, maxResults, pageToken): parser.parse(self.args, request) return self.get_paginated_list(Categories, maxResults, categories_fields, pageToken)
"""Code Analyzer API -code_analyze.""" import json from flask import current_app from flask.ext.restful import (fields, marshal, reqparse, Resource) from pylint import epylint as lint error_details = { 'line': fields.String, 'message_id': fields.String(attribute='message-id'), 'message': fields.String } format_details = {'errors': fields.Nested(error_details)} parser = reqparse.RequestParser() parser.add_argument('source_code', required=True, type=unicode, location=['json', 'form'], help='Source code required to run formatting.') class CodeAnalyze(Resource): """Handle requests related to source code formatting.""" def post(self): """ Save the posted data into a temporary file. Check the saved file for errors/formatting issues.
# Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io from flask.ext.restful import Resource, fields, marshal_with from jormungandr import i_manager from make_links import add_coverage_link, add_coverage_link, add_collection_links, clean_links from converters_collection_type import collections_to_resource_type from collections import OrderedDict from fields import NonNullNested region_fields = { "id": fields.String(attribute="region_id"), "start_production_date": fields.String, "end_production_date": fields.String, "status": fields.String, "shape": fields.String, "error": NonNullNested({ "code": fields.String, "value": fields.String }) } regions_fields = OrderedDict([ ("regions", fields.List(fields.Nested(region_fields))) ]) collections = collections_to_resource_type.keys()
user_parser.add_argument('phone', type=str, required=True, help="phone cannot be blank!") user_parser.add_argument('nickname', type=str, required=True) user_parser.add_argument('password', type=str, required=True) # From the request headers # parser.add_argument('User-Agent', type=str, location='headers') # Marshaled field definitions for user objects user_fields = { 'id': fields.Integer, 'phone': fields.String, 'nickname': fields.String, 'token': fields.String(attribute='token', default=''), } # Marshaled field definitions for list of user objects user_list_fields = { 'id': fields.Integer, 'phone': fields.String, 'nickname': fields.String, } def abort_if_user_doesnt_exist(userid): user = User.get_by_id(userid) if user is None: abort(404, message="User {} doesn't exist".format(userid)) return user
if obj.code != '': return obj.code else: if obj.name != '': return obj.name class get_key_value(fields.Raw): def output(self, key, obj): res = {} for code in obj.properties: res[code.type] = code.value return res code = {"type": fields.String(), "value": fields.String()} generic_message = { "level": enum_type(attribute="message_status"), "value": fields.String(attribute="message"), "start_application_date": fields.String(), "end_application_date": fields.String(), "start_application_daily_hour": fields.String(), "end_application_daily_hour": fields.String(), } display_informations_route = { "network": fields.String(attribute="network"), "direction": fields.String(attribute="direction"), "commercial_mode": fields.String(attribute="commercial_mode"), "label": get_label(attribute="display_information"),
class ldapNode(BaseModel): # Swager Doc resource_fields = { 'id': fields.String(attribute='Node unique identifier'), 'type': fields.String(attribute='Node type'), 'cluster_id': fields.String(attribute='Cluster ID'), 'local_hostname': fields.String( attribute='Local hostname of the node (not the cluster hostname).' ), 'ip': fields.String(attribute='IP address of the node'), 'ldap_binddn': fields.String( attribute= 'LDAP super user Bind DN. Probably should leave it default cn=directory manager.' ), 'ldap_port': fields.String(attribute='Non SSL LDAP port (not used)'), 'ldaps_port': fields.String(attribute='LDAPS port'), 'ldap_admin_port': fields.String(attribute='Admin port'), 'ldap_jmx_port': fields.String(attribute='JMX port (not used)'), } def __init__(self): self.install_dir = "" self.ldap_type = "opendj" self.local_hostname = "" self.ip = "" # Filesystem path of the opendj-setup.properties template self.ldap_setup_properties = "api/templates/salt/opendj/opendj-setup.properties" # Filesystem path of the public certificate for OpenDJ self.openDjCertFn = '/etc/certs/opendj.crt' self.ldap_binddn = 'cn=directory manager' self.ldap_port = '1389' self.ldaps_port = '1636' self.ldap_jmx_port = '1689' self.ldap_admin_port = '4444' self.ldap_replication_port = "8989" # Where to install OpenDJ, usually /opt/opendj self.ldapBaseFolder = '/opt/opendj' # How long to wait for LDAP to start self.ldapStartTimeOut = 30 # Full path to opendj setup command self.ldapSetupCommand = '%s/setup' % self.ldapBaseFolder # Full path to dsconfig command self.ldapDsconfigCommand = "%s/bin/dsconfig" % self.ldapBaseFolder # Full path to create-rc command self.ldapDsCreateRcCommand = "%s/bin/create-rc-script" % self.ldapBaseFolder # Full path to dsjavaproperties command self.ldapDsJavaPropCommand = "%s/bin/dsjavaproperties" % self.ldapBaseFolder # Full path to import command self.importLdifCommand = '%s/bin/import-ldif' % self.ldapBaseFolder # Full path to encode password self.ldapEncodePWCommand = '%s/bin/encode-password' % self.ldapBaseFolder # Temporary path to store ldap password (should be removed) self.ldapPassFn = '/home/ldap/.pw' # Full path of template schema to copy to the opendj server self.schemaFolder = "%s/template/config/schema" % self.ldapBaseFolder self.org_custom_schema = "%s/config/schema/100-user.ldif" % self.ldapBaseFolder self.schemaFiles = [ "api/templates/salt/opendj/schema/101-ox.ldif", "api/templates/salt/opendj/schema/77-customAttributes.ldif", "api/templates/salt/opendj/schema/96-eduperson.ldif", "api/templates/salt/opendj/schema/100-user.ldif", ] # Full path of template init file self.init_file = '%s/static/opendj/opendj' % self.install_dir # Full path of the destination of the init script self.ldap_start_script = '/etc/init.d/opendj' # Full path to java keytool command self.keytoolCommand = '/usr/bin/keytool' # self.keytoolCommand = '/usr/java/latest/bin/keytool' # Full path to openssl command self.opensslCommand = '/usr/bin/openssl' self.outputFolder = '/tmp' self.ldif_base = 'api/templates/salt/opendj/ldif/base.ldif' self.ldif_appliance = 'api/templates/salt/opendj/ldif/appliance.ldif' self.ldif_attributes = 'api/templates/salt/opendj/ldif/attributes.ldif' self.ldif_scopes = 'api/templates/salt/opendj/ldif/scopes.ldif' self.ldif_clients = 'api/templates/salt/opendj/ldif/clients.ldif' self.ldif_people = 'api/templates/salt/opendj/ldif/people.ldif' self.ldif_groups = 'api/templates/salt/opendj/ldif/groups.ldif' self.ldif_site = 'api/templates/salt/opendj/ldif/o_site.ldif' self.ldif_scripts = 'api/templates/salt/opendj/ldif/scripts.ldif' # List of initial ldif files self.ldif_files = [ self.ldif_base, self.ldif_appliance, self.ldif_attributes, self.ldif_scopes, self.ldif_clients, self.ldif_people, self.ldif_groups, self.ldif_site, self.ldif_scripts, ] self.id = '' self.name = '' self.type = 'ldap' self.cluster_name = "" self.defaultTrustStoreFN = '/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/security/cacerts' self.indexJson = "api/templates/salt/opendj/opendj_index.json"
def output(self, key, region): if 'timezone' in region and key in region: dt = datetime.datetime.utcfromtimestamp(region[key]) tz = pytz.timezone(region["timezone"]) if tz: dt = pytz.utc.localize(dt) dt = dt.astimezone(tz) return dt.strftime("%Y%m%dT%H%M%S") else: return None else: return None validity_pattern = { 'beginning_date': fields.String(), 'days': fields.String(), } trip = { 'id': fields.String(attribute="uri"), 'name': fields.String(), } code = {"type": fields.String(), "value": fields.String()} prop = {"name": fields.String(), "value": fields.String()} period = { "begin": DateTime(), "end": DateTime(),