text stringlengths 0 1.05M | meta dict |
|---|---|
# api.py
# Ronald L. Rivest
# July 29, 2016
# python3
"""
This is a draft API as a possible interface between the
Bayesian audit code (or other audit code) and the implementation
of the STV social choice function by Grahame Bowland.
"""
##############################################################################
## Candidates
"""
A candidate is represented by the Candidate named-tuple datatype
as defined in dividbatur senatecount.py. A candidate has attributes:
CandidateID # integer
Surname # string
GivenNm # string
PartyNm # string
"""
##############################################################################
## Ballot (preference tuple)
"""
A ballot is a tuple of candidate_ids, in order of decreasing preference.
It may have any length, possibly less than the number of candidates;
candidates not mentioned are preferred less than those mentioned.
One may think of this as the (BTL) form of a single cast paper ballot.
(It could alternatively be a tuple of (preference_no, candidate_id) pairs,
as long as it is hashable, and things are sorted into order. But I prefer
the simpler tuple of candidate_ids.)
"""
##############################################################################
## Election
class Election:
"""
An Election represents the basic information about an election,
including candidates, number of seats available, list of cast
ballots (with multiplicities), etc.
"""
def __init__(self):
self.electionID = "NoElection" # string
self.seats = 0 # integer
self.candidate_ids = [] # list of candidate_ids
self.candidates = [] # list of candidates
self.ballots = [] # list of ballots
self.ballot_weights = {} # dict mapping ballots to weights
self.total_ballot_weight = 0.0 # sum of all ballot weights
"""
ballot_weights is a python dict mapping ballots in self.ballots to weights that are >= 0.
These weights are *not* modified by the counting; they always
represent the number of times each preference list was input as a ballot.
These weights need *not* be integers.
"""
def load_election(self, dirname):
"""
Load election data from files in the specified directory. Sets
self.electionID
self.seats
self.candidate_ids
self.candidates
self.ballots
self.ballot_weights
No formality checks are made.
Translates each ATL ballot into a BTL equivalent.
"""
pass # TBD
def add_ballot(self, ballot, weight):
"""
Add BTL ballot with given weight to the election.
If ballot with same preferences already exists, then
just add to its weight.
No formality checks are made.
"""
if ballot in self.ballot_weights:
self.ballot_weights[ballot] += weight
else:
self.ballots.append(ballot)
self.ballot_weights[ballot] = weight
self.total_ballot_weight += weight
def load_more_ballots(self, filename):
"""
repeat add_ballot on each new BTL ballot from file with given filename,
each with weight 1
"""
pass # TBD
def get_outcome(self, new_ballot_weights=None, **params):
"""
Return list of candidates who are elected in this election, where
self.ballot_weights gives weights of each ballot.
However, if new_ballot_weights is given, use those instead
of self.ballot_weights.
params is dict giving parameters that may affect how computation
is done, such as tie-breaking info, or number n of ballots cast overall
in election (not just sample size).
params may also control output (e.g. logging output).
"""
pass # TBD
| {
"repo_name": "ron-rivest/2016-aus-senate-audit",
"path": "rivest/api.py",
"copies": "1",
"size": "4057",
"license": "apache-2.0",
"hash": 8978367834118833000,
"line_mean": 33.6752136752,
"line_max": 97,
"alpha_frac": 0.5824500863,
"autogenerated": false,
"ratio": 4.482872928176795,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5565323014476795,
"avg_score": null,
"num_lines": null
} |
""" API relating to configuration """
from flask_restful import fields, inputs, marshal, marshal_with, Resource
from flask_security import login_required
from .base import BaseDetailResource, BaseRequestParser
from .fields import NonBlankInput
from .util import new_edit_parsers
from dockci.models.auth import AuthenticatedRegistry
from dockci.server import API, DB
from dockci.util import AGENT_PERMISSION
REGISTRY_BASIC_FIELDS = {
'display_name': fields.String(),
'base_name': fields.String(),
'username': fields.String(),
'email': fields.String(),
'insecure': fields.Boolean(),
'detail': fields.Url('registry_detail'),
}
REGISTRY_AGENT_FIELDS = {
'password': fields.String(),
}
REGISTRY_AGENT_FIELDS.update(REGISTRY_BASIC_FIELDS)
REGISTRY_SHARED_PARSER_ARGS = {
'display_name': dict(
help="Registry display name",
required=None, type=NonBlankInput(),
),
'username': dict(help="Username for logging into the registry"),
'password': dict(help="Password for logging into the registry"),
'email': dict(help="Email for logging into the registry"),
'insecure': dict(
help="Whether connection is over HTTP (default HTTPS)",
required=None, type=inputs.boolean,
)
}
REGISTRY_NEW_PARSER = BaseRequestParser()
REGISTRY_EDIT_PARSER = BaseRequestParser()
new_edit_parsers(REGISTRY_NEW_PARSER,
REGISTRY_EDIT_PARSER,
REGISTRY_SHARED_PARSER_ARGS)
# pylint:disable=no-self-use
class RegistryList(Resource):
""" API resource that handles listing registries """
@login_required
@marshal_with(REGISTRY_BASIC_FIELDS)
def get(self):
""" List of all projects """
return AuthenticatedRegistry.query.all()
class RegistryDetail(BaseDetailResource):
"""
API resource to handle getting registry details, creating new registries,
updating existing registries, and deleting registries
"""
@login_required
def get(self, base_name):
""" Get registry details """
registry = AuthenticatedRegistry.query.filter_by(
base_name=base_name,
).first_or_404()
marshaler = (REGISTRY_AGENT_FIELDS
if AGENT_PERMISSION.can() else
REGISTRY_BASIC_FIELDS)
return marshal(registry, marshaler)
@login_required
@marshal_with(REGISTRY_BASIC_FIELDS)
def put(self, base_name):
""" Create a new registry """
registry = AuthenticatedRegistry(base_name=base_name)
return self.handle_write(registry, REGISTRY_NEW_PARSER)
@login_required
@marshal_with(REGISTRY_BASIC_FIELDS)
def post(self, base_name):
""" Update an existing registry """
registry = AuthenticatedRegistry.query.filter_by(
base_name=base_name,
).first_or_404()
return self.handle_write(registry, REGISTRY_EDIT_PARSER)
@login_required
def delete(self, base_name):
""" Delete a registry """
registry = AuthenticatedRegistry.query.filter_by(
base_name=base_name,
).first_or_404()
display_name = registry.display_name
DB.session.delete(registry)
DB.session.commit()
return {'message': '%s deleted' % display_name}
API.add_resource(RegistryList,
'/registries',
endpoint='registry_list')
API.add_resource(RegistryDetail,
'/registries/<string:base_name>',
endpoint='registry_detail')
| {
"repo_name": "RickyCook/DockCI",
"path": "dockci/api/config.py",
"copies": "2",
"size": "3511",
"license": "isc",
"hash": 7396637289790822000,
"line_mean": 30.9181818182,
"line_max": 77,
"alpha_frac": 0.6550840216,
"autogenerated": false,
"ratio": 3.9943117178612058,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5649395739461206,
"avg_score": null,
"num_lines": null
} |
""" API relating to Job model objects """
import sqlalchemy
import uuid
import flask_restful
import redis
import redis_lock
from flask import abort, request, url_for
from flask_restful import fields, inputs, marshal_with, Resource
from flask_security import current_user, login_required
from . import fields as fields_
from .base import BaseDetailResource, BaseRequestParser
from .fields import datetime_or_now, GravatarUrl, NonBlankInput, RewriteUrl
from .util import DT_FORMATTER
from dockci.models.job import Job, JobResult, JobStageTmp
from dockci.models.project import Project
from dockci.server import API, CONFIG, pika_conn, redis_pool
from dockci.stage_io import redis_len_key, redis_lock_name
from dockci.util import str2bool, require_agent
BASIC_FIELDS = {
'slug': fields.String(),
'state': fields.String(),
'commit': fields.String(),
'create_ts': DT_FORMATTER,
'tag': fields.String(),
'git_branch': fields.String(),
'git_author_avatar': GravatarUrl(attr_name='git_author_email'),
}
LIST_FIELDS = {
'detail': RewriteUrl('job_detail', rewrites=dict(
project_slug='project.slug',
job_slug='slug',
)),
}
LIST_FIELDS.update(BASIC_FIELDS)
ITEMS_MARSHALER = fields.List(fields.Nested(LIST_FIELDS))
ALL_LIST_ROOT_FIELDS = {
'items': ITEMS_MARSHALER,
'meta': fields.Nested({
'total': fields.Integer(default=None),
}),
}
STAGE_DETAIL_FIELDS = {
'success': fields.Boolean(),
}
STAGE_LIST_FIELDS = {
'slug': fields.String(),
'success': fields.Boolean(),
}
CREATE_FIELDS = {
'project_detail': RewriteUrl('project_detail', rewrites=dict(
project_slug='project.slug',
)),
'display_repo': fields.String(),
}
CREATE_FIELDS.update(LIST_FIELDS)
DETAIL_FIELDS = {
'ancestor_detail': RewriteUrl('job_detail', rewrites=dict(
project_slug='project.slug',
job_slug='ancestor_job.slug',
)),
'project_detail': RewriteUrl('project_detail', rewrites=dict(
project_slug='project.slug',
)),
'project_slug': fields.String(),
'job_stage_slugs': fields.List(fields.String),
'start_ts': DT_FORMATTER,
'complete_ts': DT_FORMATTER,
'display_repo': fields.String(),
'image_id': fields.String(),
'container_id': fields.String(),
'docker_client_host': fields.String(),
'exit_code': fields.Integer(default=None),
'result': fields.String(),
'git_author_name': fields.String(),
'git_author_email': fields.String(),
'git_committer_name': fields.String(),
'git_committer_email': fields.String(),
'git_committer_avatar': GravatarUrl(attr_name='git_committer_email'),
}
DETAIL_FIELDS.update(BASIC_FIELDS)
DETAIL_FIELDS.update(CREATE_FIELDS)
JOB_NEW_PARSER = BaseRequestParser()
JOB_NEW_PARSER.add_argument('commit',
required=True,
type=fields_.strip(NonBlankInput()),
help="Git ref to check out")
JOB_EDIT_PARSER = BaseRequestParser()
JOB_EDIT_PARSER.add_argument('start_ts', type=datetime_or_now)
JOB_EDIT_PARSER.add_argument('complete_ts', type=datetime_or_now)
JOB_EDIT_PARSER.add_argument('result',
choices=tuple(JobResult.__members__) + (None,))
JOB_EDIT_PARSER.add_argument('commit')
JOB_EDIT_PARSER.add_argument('tag')
JOB_EDIT_PARSER.add_argument('image_id')
JOB_EDIT_PARSER.add_argument('container_id')
JOB_EDIT_PARSER.add_argument('exit_code')
JOB_EDIT_PARSER.add_argument('git_branch')
JOB_EDIT_PARSER.add_argument('git_author_name')
JOB_EDIT_PARSER.add_argument('git_author_email')
JOB_EDIT_PARSER.add_argument('git_committer_name')
JOB_EDIT_PARSER.add_argument('git_committer_email')
JOB_EDIT_PARSER.add_argument('ancestor_job_id')
STAGE_EDIT_PARSER = BaseRequestParser()
STAGE_EDIT_PARSER.add_argument('success', type=inputs.boolean)
def get_validate_job(project_slug, job_slug):
""" Get the job object, validate that project slug matches expected """
job_id = Job.id_from_slug(job_slug)
job = Job.query.get_or_404(job_id)
if job.project.slug != project_slug:
flask_restful.abort(404)
if not (job.project.public or current_user.is_authenticated()):
flask_restful.abort(404)
return job
def stage_from_job(job, stage_slug):
""" Get a stage object from a job """
try:
return next(
stage for stage in job.job_stages
if stage.slug == stage_slug
)
except StopIteration:
return None
def get_validate_stage(project_slug, job_slug, stage_slug):
""" Get a stage from a validated job """
job = get_validate_job(project_slug, job_slug)
stage = stage_from_job(job, stage_slug)
if stage is None:
abort(404)
return stage
def filter_jobs_by_request(project):
""" Get all jobs for a project, filtered by some request parameters """
filter_args = {}
for filter_name in ('passed', 'versioned', 'completed'):
try:
value = request.values[filter_name]
if value == '': # Acting as a switch
filter_args[filter_name] = True
else:
filter_args[filter_name] = str2bool(value)
except KeyError:
pass
for filter_name in ('branch', 'tag', 'commit'):
try:
filter_args[filter_name] = request.values[filter_name]
except KeyError:
pass
return Job.filtered_query(
query=project.jobs.order_by(sqlalchemy.desc(Job.create_ts)),
**filter_args
)
# pylint:disable=no-self-use
class JobList(BaseDetailResource):
""" API resource that handles listing, and creating jobs """
@marshal_with(ALL_LIST_ROOT_FIELDS)
def get(self, project_slug):
""" List all jobs for a project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.public or current_user.is_authenticated()):
flask_restful.abort(404)
base_query = filter_jobs_by_request(project)
return {
'items': base_query.paginate().items,
'meta': {'total': base_query.count()},
}
@login_required
@marshal_with(CREATE_FIELDS)
def post(self, project_slug):
""" Create a new job for a project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
job = Job(project=project, repo_fs=project.repo_fs)
self.handle_write(job, JOB_NEW_PARSER)
job.queue()
return job
class JobCommitsList(Resource):
""" API resource to handle getting commit lists """
def get(self, project_slug):
""" List all distinct job commits for a project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.public or current_user.is_authenticated()):
flask_restful.abort(404)
base_query = filter_jobs_by_request(project).filter(
Job.commit.op('SIMILAR TO')(r'[0-9a-fA-F]+')
)
commit_query = base_query.from_self(Job.commit).distinct(Job.commit)
return {
'items': [
res_arr[0] for res_arr in commit_query.paginate().items
],
'meta': {'total': commit_query.count()},
}
class JobDetail(BaseDetailResource):
""" API resource to handle getting job details """
@marshal_with(DETAIL_FIELDS)
def get(self, project_slug, job_slug):
""" Show job details """
return get_validate_job(project_slug, job_slug)
@require_agent
@marshal_with(DETAIL_FIELDS)
def patch(self, project_slug, job_slug):
""" Update a job """
job = get_validate_job(project_slug, job_slug)
previous_state = job.state
self.handle_write(job, JOB_EDIT_PARSER)
new_state = job.state
if new_state != previous_state:
if job.project.is_external:
job.send_external_status()
if job.is_complete and job.changed_result():
job.send_email_notification()
return job
class StageList(Resource):
""" API resource that handles listing stages for a job """
@marshal_with(STAGE_LIST_FIELDS)
def get(self, project_slug, job_slug):
""" List all stage slugs for a job """
def match(stage):
""" Matches stages against query parameters """
return not (
'slug' in request.values and
request.values['slug'] not in stage.slug
)
return [
stage for stage in
get_validate_job(project_slug, job_slug).job_stages
if match(stage)
]
class StageDetail(BaseDetailResource):
""" API resource to handle getting stage details """
@marshal_with(STAGE_DETAIL_FIELDS)
def get(self, project_slug, job_slug, stage_slug):
""" Show job stage details """
return get_validate_stage(project_slug, job_slug, stage_slug)
@require_agent
@marshal_with(STAGE_DETAIL_FIELDS)
def put(self, project_slug, job_slug, stage_slug):
""" Update a job stage """
job = get_validate_job(project_slug, job_slug)
stage = stage_from_job(job, stage_slug)
created = True if stage is None else False
if created:
stage = JobStageTmp(slug=stage_slug, job=job)
return self.handle_write(stage, STAGE_EDIT_PARSER)
class ArtifactList(Resource):
""" API resource that handles listing artifacts for a job """
def get(self, project_slug, job_slug):
""" List output details for a job """
return get_validate_job(project_slug, job_slug).job_output_details
class StageStreamDetail(Resource):
""" API resource to handle creating stage stream queues """
def post(self, project_slug, job_slug):
""" Create a new stream queue for a job """
job = get_validate_job(project_slug, job_slug)
routing_key = 'dockci.{project_slug}.{job_slug}.*.*'.format(
project_slug=project_slug,
job_slug=job_slug,
)
with redis_pool() as redis_pool_:
with pika_conn() as pika_conn_:
channel = pika_conn_.channel()
queue_result = channel.queue_declare(
queue='dockci.job.%s' % uuid.uuid4().hex,
arguments={
'x-expires': CONFIG.live_log_session_timeout,
'x-message-ttl': CONFIG.live_log_message_timeout,
},
durable=False,
)
redis_conn = redis.Redis(connection_pool=redis_pool_)
with redis_lock.Lock(
redis_conn,
redis_lock_name(job),
expire=5,
):
channel.queue_bind(
exchange='dockci.job',
queue=queue_result.method.queue,
routing_key=routing_key,
)
try:
stage = job.job_stages[-1]
except IndexError:
stage = None
bytes_read = 0
else:
bytes_read = redis_conn.get(
redis_len_key(stage)
)
# Sometimes Redis gives us bytes :\
try:
bytes_read = bytes_read.decode()
except AttributeError:
pass
return {
'init_stage': None if stage is None else stage.slug,
'init_log': None if stage is None else (
"{url}?count={count}".format(
url=url_for(
'job_log_init_view',
project_slug=project_slug,
job_slug=job_slug,
stage=stage.slug
),
count=bytes_read,
)
),
'live_queue': queue_result.method.queue,
}
API.add_resource(
JobList,
'/projects/<string:project_slug>/jobs',
endpoint='job_list',
)
API.add_resource(
JobCommitsList,
'/projects/<string:project_slug>/jobs/commits',
endpoint='job_commits_list',
)
API.add_resource(
JobDetail,
'/projects/<string:project_slug>/jobs/<string:job_slug>',
endpoint='job_detail',
)
API.add_resource(
StageList,
'/projects/<string:project_slug>/jobs/<string:job_slug>/stages',
endpoint='stage_list',
)
API.add_resource(
StageDetail,
'/projects/<string:project_slug>/jobs/<string:job_slug>'
'/stages/<string:stage_slug>',
endpoint='stage_detail',
)
# API.add_resource(
# ArtifactList,
# '/projects/<string:project_slug>/jobs/<string:job_slug>/artifacts',
# endpoint='artifact_list',
# )
API.add_resource(
StageStreamDetail,
'/projects/<string:project_slug>/jobs/<string:job_slug>/stream',
endpoint='stage_stream_detail',
)
| {
"repo_name": "RickyCook/DockCI",
"path": "dockci/api/job.py",
"copies": "2",
"size": "13097",
"license": "isc",
"hash": -629299873998329900,
"line_mean": 30.7888349515,
"line_max": 76,
"alpha_frac": 0.5942582271,
"autogenerated": false,
"ratio": 3.786354437698757,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 412
} |
""" API relating to JWT authentication """
from datetime import datetime
import jwt
from flask import url_for
from flask_restful import Resource
from flask_security import current_user, login_required
from .base import BaseRequestParser
from .exceptions import OnlyMeError, WrappedTokenError, WrongAuthMethodError
from .fields import NonBlankInput
from .util import clean_attrs, DT_FORMATTER, ensure_roles_found
from dockci.models.auth import lookup_role
from dockci.server import API, CONFIG
from dockci.util import require_admin, jwt_token
JWT_ME_DETAIL_PARSER = BaseRequestParser()
JWT_NEW_PARSER = BaseRequestParser()
JWT_NEW_PARSER.add_argument('name',
required=True, type=NonBlankInput(),
help="Service name for the token")
JWT_NEW_PARSER.add_argument('exp',
type=DT_FORMATTER,
help="Expiration time of the token")
JWT_SERVICE_NEW_PARSER = JWT_NEW_PARSER.copy()
JWT_SERVICE_NEW_PARSER.add_argument('roles',
required=True, action='append',
help="Roles the service is given")
# pylint:disable=no-self-use
class JwtNew(Resource):
""" API resource that handles creating JWT tokens for users """
@login_required
def post(self, user_id):
""" Create a JWT token for a user """
if current_user.id != user_id:
raise OnlyMeError("create JWT tokens")
args = JWT_NEW_PARSER.parse_args(strict=True)
args = clean_attrs({
'name': args['name'],
'exp': args['exp'],
})
return {'token': jwt_token(**args)}, 201
class JwtServiceNew(Resource):
""" API resource that handles creating new JWT tokens for services """
@login_required
@require_admin
def post(self):
""" Create a JWT token for a service user """
args = JWT_SERVICE_NEW_PARSER.parse_args(strict=True)
args = clean_attrs({
'name': args['name'],
'exp': args['exp'],
'roles': args['roles'],
})
found_roles = [
role for role in [
lookup_role(name)
for name in args['roles']
]
if role is not None
]
ensure_roles_found(args['roles'], found_roles)
return {'token': jwt_token(sub='service', **args)}, 201
class JwtMeDetail(Resource):
"""
API resource to handle getting current JWT token details, and creating one
for the current user
"""
@login_required
def get(self):
""" Get details about the current JWT token """
args = JWT_ME_DETAIL_PARSER.parse_args()
api_key = args['x_dockci_api_key'] or args['hx_dockci_api_key']
if api_key is None:
raise WrongAuthMethodError("a JWT token")
else:
return JwtDetail().get(api_key)
@login_required
def post(self):
""" Create a JWT token for the currently logged in user """
return JwtNew().post(current_user.id)
class JwtDetail(Resource):
""" API resource to handle getting job details """
def get(self, token):
""" Get details about a JWT token """
try:
jwt_data = jwt.decode(token, CONFIG.secret)
except jwt.exceptions.InvalidTokenError as ex:
raise WrappedTokenError(ex)
jwt_data['iat'] = DT_FORMATTER.format(
datetime.fromtimestamp(jwt_data['iat'])
)
try:
user_id = jwt_data['sub']
jwt_data['sub_detail'] = url_for('user_detail', user_id=user_id)
except KeyError:
pass
return jwt_data
API.add_resource(JwtNew,
'/users/<int:id>/jwt',
endpoint='jwt_user_new')
API.add_resource(JwtServiceNew,
'/jwt/service',
endpoint='jwt_service_new')
API.add_resource(JwtMeDetail,
'/me/jwt',
endpoint='jwt_me_detail')
API.add_resource(JwtDetail,
'/jwt/<string:token>',
endpoint='jwt_detail')
| {
"repo_name": "sprucedev/DockCI",
"path": "dockci/api/jwt.py",
"copies": "2",
"size": "4139",
"license": "isc",
"hash": -4344735773071061500,
"line_mean": 30.3560606061,
"line_max": 78,
"alpha_frac": 0.5834742691,
"autogenerated": false,
"ratio": 3.923222748815166,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 132
} |
""" API relating to Project model objects """
import re
import flask_restful
import sqlalchemy
from flask import request
from flask_restful import (fields,
inputs,
marshal,
marshal_with,
reqparse,
Resource,
)
from flask_security import current_user, login_required
from sqlalchemy.sql import functions as sql_func
from .base import BaseDetailResource, BaseRequestParser
from .exceptions import NoModelError, WrappedValueError
from .fields import (GravatarUrl,
NonBlankInput,
RegexField,
RegexInput,
RewriteUrl,
)
from .util import (clean_attrs,
DT_FORMATTER,
new_edit_parsers,
)
from dockci.models.auth import AuthenticatedRegistry
from dockci.models.job import Job
from dockci.models.project import Project
from dockci.server import API
DOCKER_REPO_RE = re.compile(r'^[a-z0-9]+(?:[._-][a-z0-9]+)*$')
def docker_repo_field(value, name):
""" User input validation that a value is a valid Docker image name """
if not DOCKER_REPO_RE.match(value):
raise ValueError(("Invalid %s. Must start with a lower case, "
"alphanumeric character, and contain only the "
"additional characters '-', '_' and '.'") % name)
return value
BASIC_FIELDS = {
'name': fields.String(),
'slug': fields.String(),
'utility': fields.Boolean(),
'status': fields.String(),
'display_repo': fields.String(),
}
LIST_FIELDS = {
'detail': RewriteUrl('project_detail', rewrites=dict(project_slug='slug')),
}
LIST_FIELDS.update(BASIC_FIELDS)
LATEST_JOB_FIELDS = {
'slug': fields.String(),
'detail': RewriteUrl('job_detail', rewrites=dict(
project_slug='project.slug',
job_slug='slug',
)),
'state': fields.String(),
'create_ts': DT_FORMATTER,
'git_author_avatar': GravatarUrl(attr_name='git_author_email')
}
LIST_FIELDS_LATEST_JOB = {
'latest_job': fields.Nested(
LATEST_JOB_FIELDS,
attribute=lambda project: project.latest_job(),
allow_null=True,
),
}
LIST_FIELDS_LATEST_JOB.update(LIST_FIELDS)
ITEMS_MARSHALER = fields.List(fields.Nested(LIST_FIELDS))
ITEMS_MARSHALER_LATEST_JOB = fields.List(fields.Nested(LIST_FIELDS_LATEST_JOB))
ALL_LIST_ROOT_FIELDS = {
'items': ITEMS_MARSHALER,
'meta': fields.Nested({
'total': fields.Integer(default=None),
'success': fields.Integer(default=None),
'broken': fields.Integer(default=None),
'fail': fields.Integer(default=None),
}),
}
DETAIL_FIELDS = {
'branch_pattern': RegexField(),
'utility': fields.Boolean(),
'github_repo_id': fields.String(),
'github_hook_id': fields.String(),
'gitlab_repo_id': fields.String(),
'public': fields.Boolean(),
'shield_text': fields.String(),
'shield_color': fields.String(),
'target_registry': RewriteUrl(
'registry_detail',
rewrites=dict(base_name='target_registry.base_name'),
),
}
DETAIL_FIELDS.update(BASIC_FIELDS)
BASIC_BRANCH_FIELDS = {
'name': fields.String(),
}
TARGET_REGISTRY_ARGS = ('target_registry',)
TARGET_REGISTRY_KWARGS = dict(help="Base name of the registry to push to")
TARGET_REGISTRY_ARGUMENT_NEW = reqparse.Argument(
*TARGET_REGISTRY_ARGS, required=True, **TARGET_REGISTRY_KWARGS
)
TARGET_REGISTRY_ARGUMENT_EDIT = reqparse.Argument(
*TARGET_REGISTRY_ARGS, required=False, **TARGET_REGISTRY_KWARGS
)
SHARED_PARSER_ARGS = {
'name': dict(
help="Project display name",
required=None, type=NonBlankInput(),
),
'repo': dict(
help="Git repository for the project code",
required=None, type=NonBlankInput(),
),
'branch_pattern': dict(
help="Always tag, and push branches matching this pattern",
type=RegexInput(),
),
'github_secret': dict(help="Shared secret to validate GitHub hooks"),
'public': dict(
help="Whether or not to allow read-only guest access",
type=inputs.boolean,
),
}
UTILITY_ARG = dict(
help="Whether or not this is a utility project",
type=inputs.boolean, # Implies not-null/blank
)
PROJECT_NEW_PARSER = BaseRequestParser()
PROJECT_EDIT_PARSER = BaseRequestParser()
new_edit_parsers(PROJECT_NEW_PARSER, PROJECT_EDIT_PARSER, SHARED_PARSER_ARGS)
PROJECT_NEW_UTILITY_ARG = UTILITY_ARG.copy()
PROJECT_NEW_UTILITY_ARG['required'] = True
PROJECT_NEW_PARSER.add_argument('utility', **PROJECT_NEW_UTILITY_ARG)
PROJECT_NEW_PARSER.add_argument(
'gitlab_repo_id',
help="ID of the project repository",
)
PROJECT_NEW_PARSER.add_argument(
'github_repo_id',
help="Full repository ID in GitHub",
)
PROJECT_NEW_PARSER.add_argument(TARGET_REGISTRY_ARGUMENT_NEW)
PROJECT_EDIT_PARSER.add_argument(TARGET_REGISTRY_ARGUMENT_EDIT)
PROJECT_LIST_PARSER = BaseRequestParser()
PROJECT_LIST_PARSER.add_argument(
'meta',
type=inputs.boolean,
default=False,
help="Whether to include metadata with the list",
)
PROJECT_LIST_PARSER.add_argument(
'latest_job',
type=inputs.boolean,
default=False,
help="Whether to include information about the latest job",
)
PROJECT_FILTERS_PARSER = reqparse.RequestParser()
PROJECT_FILTERS_PARSER.add_argument('utility', **UTILITY_ARG)
PROJECTS_OPTS_PARSER = reqparse.RequestParser()
PROJECTS_OPTS_PARSER.add_argument(
'order',
choices=('none', 'recent'),
default='none',
help="How to sort the projects list",
)
def set_target_registry(args):
""" Set the ``target_registry`` to the model object """
if 'target_registry' not in args:
return
if args['target_registry'] == '':
args['target_registry'] = None
return
args['target_registry'] = (
AuthenticatedRegistry.query.filter_by(
base_name=args['target_registry'])).first()
if args['target_registry'] is None:
raise NoModelError('Registry')
def ensure_target_registry(required):
""" Ensures that the ``target_registry`` is non-blank for utilities """
value, found = reqparse.Argument(
*TARGET_REGISTRY_ARGS,
required=required,
type=NonBlankInput(),
**TARGET_REGISTRY_KWARGS
).parse(request, False)
if isinstance(value, ValueError):
flask_restful.abort(400, message=found)
# pylint:disable=no-self-use
class ProjectList(Resource):
""" API resource that handles listing projects """
def get(self):
""" List of all projects """
opts = PROJECTS_OPTS_PARSER.parse_args()
filters = PROJECT_FILTERS_PARSER.parse_args()
filters = clean_attrs(filters)
query = Project.query
if not current_user.is_authenticated():
query = query.filter_by(public=True)
if opts['order'] == 'recent':
query = (
query.
join(Project.jobs, isouter=True).
group_by(Project).
order_by(sql_func.max(Job.create_ts).desc().nullslast())
)
if filters:
query = query.filter(*[
getattr(Project, field) == value
for field, value in filters.items()
])
marshaler = dict(items=ALL_LIST_ROOT_FIELDS['items'])
values = dict(items=query.all())
args = PROJECT_LIST_PARSER.parse_args()
if args['meta']:
marshaler['meta'] = ALL_LIST_ROOT_FIELDS['meta']
values['meta'] = {'total': query.count()}
values['meta'].update(Project.get_status_summary(filters))
if args['latest_job']:
marshaler['items'] = ITEMS_MARSHALER_LATEST_JOB
return marshal(values, marshaler)
class ProjectDetail(BaseDetailResource):
"""
API resource to handle getting project details, creating new projects,
updating existing projects, and deleting projects
"""
@marshal_with(DETAIL_FIELDS)
def get(self, project_slug):
""" Get project details """
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.public or current_user.is_authenticated()):
flask_restful.abort(404)
return project
@login_required
@marshal_with(DETAIL_FIELDS)
def put(self, project_slug):
""" Create a new project """
try:
docker_repo_field(project_slug, 'slug')
except ValueError as ex:
raise WrappedValueError(ex)
args = PROJECT_NEW_PARSER.parse_args(strict=True)
args = clean_attrs(args)
args['slug'] = project_slug
if 'gitlab_repo_id' in args:
args['external_auth_token'] = (
current_user.oauth_token_for('gitlab'))
elif 'github_repo_id' in args:
args['external_auth_token'] = (
current_user.oauth_token_for('github'))
if args['utility']: # Utilities must have target registry set
ensure_target_registry(True)
set_target_registry(args)
return self.handle_write(Project(), data=args)
@login_required
@marshal_with(DETAIL_FIELDS)
def post(self, project_slug):
""" Update an existing project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
args = PROJECT_EDIT_PARSER.parse_args(strict=True)
args = clean_attrs(args)
if args.get('utility', project.utility):
ensure_target_registry(False)
set_target_registry(args)
return self.handle_write(project, data=args)
@login_required
def delete(self, project_slug):
""" Delete a project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
project_name = project.name
project.purge()
return {'message': '%s deleted' % project_name}
class ProjectBranchList(Resource):
""" API resource that handles listing branches for a project """
@marshal_with(BASIC_BRANCH_FIELDS)
def get(self, project_slug):
""" List of all branches in a project """
project = Project.query.filter_by(slug=project_slug).first_or_404()
if not (project.public or current_user.is_authenticated()):
flask_restful.abort(404)
return [
dict(name=job.git_branch)
for job
in (
project.jobs.distinct(Job.git_branch)
.order_by(sqlalchemy.asc(Job.git_branch))
)
if job.git_branch is not None
]
API.add_resource(ProjectList,
'/projects',
endpoint='project_list')
API.add_resource(ProjectDetail,
'/projects/<string:project_slug>',
endpoint='project_detail')
API.add_resource(ProjectBranchList,
'/projects/<string:project_slug>/branches',
endpoint='project_branch_list')
| {
"repo_name": "sprucedev/DockCI",
"path": "dockci/api/project.py",
"copies": "2",
"size": "11089",
"license": "isc",
"hash": -8627121471096461000,
"line_mean": 29.5482093664,
"line_max": 79,
"alpha_frac": 0.6171882045,
"autogenerated": false,
"ratio": 3.8370242214532873,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5454212425953288,
"avg_score": null,
"num_lines": null
} |
""" API relating to User model objects """
from flask import abort
from flask_restful import abort as rest_abort
from flask_restful import fields, inputs, marshal_with, Resource
from flask_security import current_user, login_required
from flask_security.changeable import change_user_password
from .base import BaseDetailResource, BaseRequestParser
from .fields import GravatarUrl, NonBlankInput, RewriteUrl
from .util import (clean_attrs,
DT_FORMATTER,
ensure_roles_found,
new_edit_parsers,
)
from dockci.models.auth import Role, User, UserEmail
from dockci.server import API, APP, CONFIG, DB
from dockci.util import ADMIN_PERMISSION, require_me_or_admin
BASIC_FIELDS = {
'id': fields.Integer(),
'email': fields.String(),
'active': fields.Boolean(),
}
LIST_FIELDS = {
'detail': RewriteUrl('user_detail', rewrites=dict(user_id='id')),
}
LIST_FIELDS.update(BASIC_FIELDS)
ROLE_FIELDS = {
'name': fields.String(),
'description': fields.String(),
}
DETAIL_FIELDS = {
'avatar': GravatarUrl(attr_name='email'),
'confirmed_at': DT_FORMATTER,
'emails': fields.List(fields.String(attribute='email')),
'roles': fields.List(fields.Nested(ROLE_FIELDS)),
}
DETAIL_FIELDS.update(BASIC_FIELDS)
SHARED_PARSER_ARGS = {
'email': dict(
help="Contact email address",
required=None, type=NonBlankInput(),
),
'password': dict(
help="Password for user to authenticate",
required=None, type=NonBlankInput(),
),
'roles': dict(
help="List of roles for the user",
required=False, action='append'
),
}
USER_NEW_PARSER = BaseRequestParser()
USER_EDIT_PARSER = BaseRequestParser()
new_edit_parsers(USER_NEW_PARSER, USER_EDIT_PARSER, SHARED_PARSER_ARGS)
USER_EDIT_PARSER.add_argument('active',
help="Whether or not the user can login",
type=inputs.boolean)
SECURITY_STATE = APP.extensions['security']
ONLY_ADMIN_MSG_FS = "Only administators can %s"
# pylint:disable=no-self-use
def rest_set_roles(user, role_names):
"""
Set given roles on the user, aborting with error if some roles don't exist
"""
role_names = set(role_names)
roles = Role.query.filter(Role.name.in_(role_names)).all()
ensure_roles_found(role_names, roles)
user.roles.clear()
user.roles.extend(roles)
def rest_set_roles_perms(user, role_names):
""" Check user permissions before setting roles """
if not role_names:
return
if not ADMIN_PERMISSION.can():
rest_abort(401, message={
"roles": ONLY_ADMIN_MSG_FS % "assign roles",
})
rest_set_roles(user, role_names)
class UserList(BaseDetailResource):
""" API resource that handles listing users, and creating new users """
@login_required
@marshal_with(LIST_FIELDS)
def get(self):
""" List all users """
return User.query.all()
@marshal_with(DETAIL_FIELDS)
def post(self):
""" Create a new user """
if not CONFIG.security_registerable_form:
rest_abort(403, message="API user registration disabled")
args = USER_NEW_PARSER.parse_args(strict=True)
args = clean_attrs(args)
# TODO throttle before error
user = SECURITY_STATE.datastore.get_user(args['email'])
if user is not None:
rest_abort(400, message={
"email": "Duplicate value '%s'" % args['email'],
})
user = SECURITY_STATE.datastore.create_user(**args)
rest_set_roles_perms(user, args['roles'])
DB.session.add(user)
DB.session.commit()
return user
class RoleList(Resource):
""" API resource that handles listing roles """
@marshal_with(ROLE_FIELDS)
def get(self):
""" List all roles """
return Role.query.all()
def user_or_404(user_id=None):
""" Return a user from the security store, or 404 """
user = SECURITY_STATE.datastore.get_user(user_id)
if user is None:
return abort(404)
return user
class UserDetail(BaseDetailResource):
""" API resource that handles getting user details, and updating users """
@login_required
@marshal_with(DETAIL_FIELDS)
def get(self, user_id=None, user=None):
""" Get a user's details """
if user is not None:
return user
return user_or_404(user_id)
@login_required
@require_me_or_admin
@marshal_with(DETAIL_FIELDS)
def post(self, user_id=None, user=None):
""" Update a user """
if user is None:
user = user_or_404(user_id)
args = USER_EDIT_PARSER.parse_args(strict=True)
args = clean_attrs(args)
try:
new_password = args.pop('password')
except KeyError:
pass
else:
change_user_password(user, new_password)
rest_set_roles_perms(user, args.pop('roles'))
return self.handle_write(user, data=args)
class UserEmailDetail(Resource):
""" Deletion of user email addresses """
@login_required
@require_me_or_admin
def delete(self, email, user_id=None, user=None):
""" Delete an email from a user """
if user is None:
user = user_or_404(user_id)
email = user.emails.filter(
UserEmail.email.ilike(email),
).first_or_404()
DB.session.delete(email)
DB.session.commit()
return {'message': '%s deleted' % email.email}
class UserRoleDetail(Resource):
""" Removal of user roles """
@login_required
def delete(self, role_name, user_id=None, user=None):
""" Remove a role from a user """
if not ADMIN_PERMISSION.can():
rest_abort(401, message=ONLY_ADMIN_MSG_FS % "remove roles")
if user is None:
user = user_or_404(user_id)
role = Role.query.filter(
Role.name.ilike(role_name),
).first_or_404()
user.roles.remove(role)
DB.session.add(user)
DB.session.commit()
return {'message': '%s removed from %s' % (
role.name,
user.email,
)}
class MeDetail(Resource):
""" Wrapper around ``UserDetail`` to user the current user """
def get(self):
""" Get details of the current user """
return UserDetail().get(user=current_user)
def post(self):
""" Update the current user """
return UserDetail().post(user=current_user)
class MeEmailDetail(Resource):
""" Deletion of user email addresses """
def delete(self, email):
""" Delete an email from the current user """
return UserEmailDetail().delete(email, user=current_user)
class MeRoleDetail(Resource):
""" Removal of user roles """
def delete(self, role_name):
""" Remove a role from the current user """
return UserRoleDetail().delete(role_name, user=current_user)
API.add_resource(UserList,
'/users',
endpoint='user_list')
API.add_resource(RoleList,
'/roles',
endpoint='role_list')
for endpoint_suffix, url_suffix, klass_user, klass_me in (
('detail', '', UserDetail, MeDetail),
('email_detail', '/emails/<string:email>', UserEmailDetail, MeEmailDetail),
('role_detail', '/roles/<string:role_name>', UserRoleDetail, MeRoleDetail),
):
API.add_resource(klass_user,
'/users/<user_id>%s' % url_suffix,
endpoint='user_%s' % endpoint_suffix)
API.add_resource(klass_me,
'/me%s' % url_suffix,
endpoint='me_%s' % endpoint_suffix)
| {
"repo_name": "RickyCook/DockCI",
"path": "dockci/api/user.py",
"copies": "2",
"size": "7739",
"license": "isc",
"hash": 5699777016078606000,
"line_mean": 28.3143939394,
"line_max": 79,
"alpha_frac": 0.6084765474,
"autogenerated": false,
"ratio": 3.7862035225048922,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 264
} |
"""APIRequestHandler subclasses for API endpoints."""
from bs4 import BeautifulSoup
from tornado.web import HTTPError, asynchronous
from tornado import gen
import pbkdf2
import logging
import yaml
from feedreader.api_request_handler import APIRequestHandler
from feedreader.database import Feed, User
logger = logging.getLogger(__name__)
class MainHandler(APIRequestHandler):
def get(self):
"""Return a hello world message."""
with self.get_db_session() as session:
username = self.require_auth(session)
self.write({"message": "Hello, {}.".format(username)})
class UsersHandler(APIRequestHandler):
def get(self):
"""Return information about the current user."""
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
username = user.username
logger.info("Returning information about user '{}'"
.format(username.encode('utf-8')))
self.write({'username': username})
self.set_status(200)
def post(self):
"""Create a new user."""
body = self.require_body_schema({
"type": "object",
"properties": {
"username": {
"type": "string",
"pattern": "^[^:\s]*$",
"maxLength": 32,
"minLength": 1
},
"password": {
"type": "string",
"minLength": 1
},
},
"required": ["username", "password"],
})
with self.get_db_session() as session:
# check if username already exists
if session.query(User).get(body["username"]) is not None:
raise HTTPError(400, reason="Username already registered")
# save new user
password_hash = pbkdf2.crypt(body["password"])
new_user = User(body["username"], password_hash)
session.add(new_user)
session.commit()
logger.info("Registered new user '{}'"
.format(body["username"].encode('utf-8')))
self.set_status(201)
class FeedsHandler(APIRequestHandler):
def get(self):
"""Return a list of the user's subscribed feeds."""
feeds = []
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
for feed in user.subscriptions:
feeds.append({
'id': feed.id,
'name': feed.title,
'url': feed.site_url,
'image_url': feed.image_url,
'unreads': user.get_num_unread_entries(feed),
})
self.write({'feeds': feeds})
self.set_status(200)
@classmethod
@gen.coroutine
def subscribe_feed(cls, session, user, celery_poller, tasks, url):
"""Subscribe the user to a feed and return the feed ID.
Raises HTTPError if the feed at the given url can't be subscribed to.
"""
# add a new feed if it doesn't exist already
feed = session.query(Feed).filter(Feed.feed_url == url).first()
if feed is None:
res = yield celery_poller.run_task(tasks.fetch_feed, url)
res = yaml.safe_load(res)
if "error" in res:
logger.warning("Failed to fetch new feed: '{}'"
.format(res['error']))
raise HTTPError(400, reason=res['error'])
feed = res['feed']
existing_feed = session.query(Feed)\
.filter(Feed.feed_url == feed.feed_url).all()
if len(existing_feed) > 0:
feed = existing_feed[0]
else:
# only add the first entry with a given guid
# this assumes the first one is the newest
entries_by_guid = {}
for entry in res['entries']:
if entry.guid not in entries_by_guid:
entries_by_guid[entry.guid] = entry
feed.add_all(entries_by_guid.values())
session.commit()
if user.has_subscription(feed):
raise HTTPError(400, reason="Already subscribed to feed")
# subscribe the user to the feed
user.subscribe(feed)
session.commit()
raise gen.Return(feed.id)
@asynchronous
@gen.coroutine
def post(self):
"""Subscribe the user to a new feed."""
body = self.require_body_schema({
'type': 'object',
'properties': {
'url': {'type': 'string'},
},
'required': ['url'],
})
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
feed_id = yield self.subscribe_feed(session, user,
self.celery_poller, self.tasks,
body['url'])
# TODO: technically this is supposed to be an absolute URL
self.set_header("Location", "/feeds/{}".format(feed_id))
self.set_status(201)
class FeedHandler(APIRequestHandler):
def get(self, feed_id):
"""Return metadata for a subscribed feed."""
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
feed = session.query(Feed).get(int(feed_id))
# Make sure the feed exists
if feed is None:
raise HTTPError(404, reason='This feed does not exist')
# Make sure the user is subscribed to this feed
if not user.has_subscription(feed):
raise HTTPError(404, reason='This feed does not exist')
self.write({
'id': feed.id,
'name': feed.title,
'url': feed.site_url,
'image_url': feed.image_url,
'unreads': user.get_num_unread_entries(feed),
})
self.set_status(200)
def delete(self, feed_id):
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
feed = session.query(Feed).get(int(feed_id))
# Make sure the feed exists
if feed is None:
raise HTTPError(404, reason='This feed does not exist')
# Make sure the user is subscribed to this feed
if not user.has_subscription(feed):
raise HTTPError(404, reason='This feed does not exist')
user.unsubscribe(feed)
self.set_status(204)
class FeedEntriesHandler(APIRequestHandler):
def get(self, feed_id):
"""Return a list of entry IDs for a feed."""
entry_filter = self.get_argument('filter', None)
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
feed = session.query(Feed).get(int(feed_id))
# Make sure the feed exists
if feed is None:
raise HTTPError(404, reason='This feed does not exist')
# Make sure the user is subscribed to this feed
if not user.has_subscription(feed):
raise HTTPError(404, reason='This feed does not exist')
# Make sure the filter keyword is valid
if entry_filter not in ['read', 'unread', None]:
raise HTTPError(400, reason='Filter keyboard is not valid')
# Get feed entries
entries = feed.get_entries(user, entry_filter)
self.write({'entries': [entry.id for entry in entries]})
self.set_status(200)
class EntriesHandler(APIRequestHandler):
@classmethod
@gen.coroutine
def truncate(cls, content, length):
return BeautifulSoup(content).get_text()[:length]
@asynchronous
@gen.coroutine
def get(self, entry_ids):
entry_ids = [int(entry_id) for entry_id in entry_ids.split(",")]
try:
length = int(self.get_argument('truncate', 0))
except ValueError:
raise HTTPError(400, reason="Invalid truncation size.")
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
entries = user.get_entries(entry_ids)
if len(entries) != len(entry_ids):
raise HTTPError(404, "Entry does not exist.")
entries_json = []
for entry in entries:
entry_json = {
"id": entry.id,
"title": entry.title,
"pub-date": entry.date,
"read": user.has_read(entry),
"author": entry.author,
"feed_id": entry.feed_id,
"url": entry.url,
}
if length:
entry_json['content'] = yield self.truncate(entry.content,
length)
else:
entry_json['content'] = entry.content
entries_json.append(entry_json)
self.write({'entries': entries_json})
self.set_status(200)
def patch(self, entry_ids):
entry_ids = [int(entry_id) for entry_id in entry_ids.split(",")]
body = self.require_body_schema({
"type": "object",
"properties": {
"read": {"type": "boolean"},
},
"required": ["read"],
})
with self.get_db_session() as session:
user = session.query(User).get(self.require_auth(session))
entries = user.get_entries(entry_ids)
if len(entries) != len(entry_ids):
raise HTTPError(404, "Entry does not exist.")
if body["read"]:
for entry in entries:
if not user.has_read(entry):
user.read(entry)
else:
for entry in entries:
if user.has_read(entry):
user.unread(entry)
self.set_status(200)
| {
"repo_name": "tdryer/feeder",
"path": "feedreader/handlers.py",
"copies": "1",
"size": "10343",
"license": "mit",
"hash": 6250767364506751000,
"line_mean": 34.9131944444,
"line_max": 79,
"alpha_frac": 0.5246060137,
"autogenerated": false,
"ratio": 4.452432199741713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5477038213441713,
"avg_score": null,
"num_lines": null
} |
'''API / request schema definitions'''
import json
import marshmallow
from marshmallow import Schema, fields, validate, post_load
class UserSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.String(required=True)
email = fields.String(required=True, validate=validate.Email())
password = fields.String(required=True, load_only=True)
active_story = fields.Nested('StorySchema', dump_only=True)
class LocationSchema(Schema):
lng = fields.Float()
lat = fields.Float()
name = fields.String()
class StoryContentSchema(Schema):
title = fields.String(required=True)
description = fields.String(required=True)
start_point = fields.Nested(LocationSchema)
end_point = fields.Nested(LocationSchema)
class StorySchema(Schema):
id = fields.Int(dump_only=True)
author_id = fields.Int(dump_only=True)
started_at = fields.DateTime()
finished_at = fields.DateTime(required=False)
updated_at = fields.DateTime(required=False)
content = fields.Nested(StoryContentSchema, required=True)
class ImageSchema(Schema):
id = fields.Int(dump_only=True)
url = fields.String(validate=validate.URL())
posted_at = fields.DateTime()
title = fields.String()
caption = fields.String()
class PostContentSchema(Schema):
title = fields.String()
images = fields.Nested(ImageSchema, many=True)
location = fields.Nested(LocationSchema)
class PostSchema(Schema):
id = fields.Int(dump_only=True)
author_id = fields.Int(dump_only=True)
posted_at = fields.DateTime()
content = fields.Nested(PostContentSchema, required=True)
user_schema = UserSchema()
story_schema = StorySchema()
post_schema = PostSchema()
post_content_schema = PostContentSchema()
| {
"repo_name": "erik/sketches",
"path": "projects/tour-story/web/web/schema.py",
"copies": "1",
"size": "1761",
"license": "mit",
"hash": 8266283756798838000,
"line_mean": 24.5217391304,
"line_max": 67,
"alpha_frac": 0.714366837,
"autogenerated": false,
"ratio": 3.623456790123457,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9837823627123456,
"avg_score": 0,
"num_lines": 69
} |
"""``Api`` resource definition module.
All of the resource classes in this module are registered with
the :class:`~apiv1.api.Api` in the main :mod:`urls.py <urls>`.
"""
from django.conf.urls.defaults import url
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.exceptions import NotFound
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from grid.models import Grid
from homepage.models import Dpotw, Gotw
from package.models import Package, Category
# TODO - exclude ID, and other fields not yet used
class BaseResource(ModelResource):
"""Base resource class - a subclass of tastypie's ``ModelResource``"""
def determine_format(self, *args, **kwargs):
"""defines all resources as returning json data"""
return "application/json"
class EnhancedModelResource(BaseResource):
def obj_get(self, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
lookup_field = getattr(self._meta, 'lookup_field', 'pk')
try:
return self._meta.queryset.get(**{lookup_field: kwargs['pk']})
except ValueError:
raise NotFound("Invalid resource lookup data provided (mismatched type).")
def get_resource_value(self, obj):
lookup_field = getattr(self._meta, 'lookup_field', 'pk')
lookups = lookup_field.split('__')
for lookup in lookups:
obj = getattr(obj, lookup)
return obj
def get_resource_uri(self, bundle_or_obj):
"""
Handles generating a resource URI for a single resource.
Uses the model's ``pk`` in order to create the URI.
"""
kwargs = {
'resource_name': self._meta.resource_name,
}
if isinstance(bundle_or_obj, Bundle):
kwargs['pk'] = self.get_resource_value(bundle_or_obj.obj)
else:
kwargs['pk'] = self.get_resource_value(bundle_or_obj)
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
return reverse("api_dispatch_detail", kwargs=kwargs)
class PackageResourceBase(EnhancedModelResource):
class Meta:
queryset = Package.objects.all()
resource_name = 'package'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
class GridResource(EnhancedModelResource):
"""Provides information about the grid.
Pulls data from the :class:`~grid.models.Grid` model.
"""
packages = fields.ToManyField(PackageResourceBase, "packages")
class Meta:
queryset = Grid.objects.all()
resource_name = 'grid'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
excludes = ["id"]
def override_urls(self):
return [
url(
r"^%s/(?P<grid_name>[-\w]+)/packages/$" % GridResource._meta.resource_name,
self.get_packages,
name='api_grid_packages',
),
]
def get_packages(self, request, **kwargs):
"""
Returns a serialized list of resources based on the identifiers
from the URL.
Pulls the data from the model :class:`~package.models.Package`.
Calls ``obj_get`` to fetch only the objects requested. This method
only responds to HTTP GET.
Should return a ``HttpResponse`` (200 OK).
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
qs = Package.objects.filter(grid__slug=kwargs['grid_name'])
pkg = PackageResource()
object_list = [pkg.full_dehydrate(obj) for obj in qs]
self.log_throttled_access(request)
return self.create_response(request, object_list)
class DpotwResource(ModelResource):
"""Package of the week resource.
Pulls data from :class:`~homepage.models.Dpotw`.
"""
class Meta:
queryset = Dpotw.objects.all()
resource_name = 'package-of-the-week'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'package__slug'
excludes = ["id"]
class GotwResource(EnhancedModelResource):
"""Grid of the week resource.
The data comes from :class:`~homepage.models.GotwResource`
"""
class Meta:
queryset = Gotw.objects.all()
resource_name = 'grid-of-the-week'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'grid__slug'
excludes = ["id"]
class CategoryResource(EnhancedModelResource):
"""Category resource.
The data is from :class:`~package.models.Category`.
"""
class Meta:
queryset = Category.objects.all()
resource_name = 'category'
allowed_methods = ['get']
lookup_field = 'slug'
excludes = ["id"]
class UserResource(EnhancedModelResource):
"""User resource.
The data is from the :class:`contrib.auth.models.User`.
Exposes ``last_login``, ``username`` and ``date_joined``.
"""
class Meta:
queryset = User.objects.all().order_by("-id")
resource_name = 'user'
allowed_methods = ['get']
lookup_field = 'username'
fields = ["resource_uri", "last_login", "username", "date_joined"]
class PackageResource(PackageResourceBase):
"""Package resource.
Pulls data from :class:`~package.models.Package` and provides
additional related data:
* :attr:`category`
* :attr:`grids`
* :attr:`created_by`
* :attr:`last_modified_by`
* :attr:`pypi_vesion`
"""
category = fields.ForeignKey(CategoryResource, "category")
grids = fields.ToManyField(GridResource, "grid_set")
created_by = fields.ForeignKey(UserResource, "created_by", null=True)
last_modified_by = fields.ForeignKey(UserResource, "created_by", null=True)
pypi_version = fields.CharField('pypi_version')
commits_over_52 = fields.CharField('commits_over_52')
usage_count = fields.CharField('get_usage_count')
class Meta:
queryset = Package.objects.all()
resource_name = 'package'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
filtering = {
"category": ALL_WITH_RELATIONS
}
| {
"repo_name": "miketheman/opencomparison",
"path": "apiv1/resources.py",
"copies": "1",
"size": "6550",
"license": "mit",
"hash": -5853212242100767000,
"line_mean": 29.6074766355,
"line_max": 91,
"alpha_frac": 0.6239694656,
"autogenerated": false,
"ratio": 4.030769230769231,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00010450382285492767,
"num_lines": 214
} |
"""``Api`` resource definition module.
All of the resource classes in this module are registered with
the :class:`~apps.apiv1.api.Api` in the main :mod:`urls.py <urls>`.
"""
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.exceptions import NotFound
from tastypie.resources import ModelResource
from django.conf.urls.defaults import url
from grid.models import Grid
from homepage.models import Dpotw, Gotw
from package.models import Package, Category
from tastypie import fields
from tastypie.resources import ModelResource
# TODO - exclude ID, repo_commits, and other fields not yet used
class BaseResource(ModelResource):
"""Base resource class - a subclass of tastypie's ``ModelResource``"""
def determine_format(self, *args, **kwargs):
"""defines all resources as returning json data"""
return "application/json"
class EnhancedModelResource(BaseResource):
def obj_get(self, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
lookup_field = getattr(self._meta, 'lookup_field', 'pk')
try:
return self._meta.queryset.get(**{lookup_field: kwargs['pk']})
except ValueError, e:
raise NotFound("Invalid resource lookup data provided (mismatched type).")
def get_resource_value(self, obj):
lookup_field = getattr(self._meta, 'lookup_field', 'pk')
lookups = lookup_field.split('__')
for lookup in lookups:
obj = getattr(obj, lookup)
return obj
def get_resource_uri(self, bundle_or_obj):
"""
Handles generating a resource URI for a single resource.
Uses the model's ``pk`` in order to create the URI.
"""
kwargs = {
'resource_name': self._meta.resource_name,
}
if isinstance(bundle_or_obj, Bundle):
kwargs['pk'] = self.get_resource_value(bundle_or_obj.obj)
else:
kwargs['pk'] = self.get_resource_value(bundle_or_obj)
if self._meta.api_name is not None:
kwargs['api_name'] = self._meta.api_name
return reverse("api_dispatch_detail", kwargs=kwargs)
class PackageResourceBase(EnhancedModelResource):
class Meta:
queryset = Package.objects.all()
resource_name = 'package'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
class GridResource(EnhancedModelResource):
"""Provides information about the grid.
Pulls data from the :class:`~apps.grid.models.Grid` model.
"""
packages = fields.ToManyField(PackageResourceBase, "packages")
class Meta:
queryset = Grid.objects.all()
resource_name = 'grid'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
excludes = ["id"]
def override_urls(self):
return [
url(
r"^%s/(?P<grid_name>[-\w]+)/packages/$" % GridResource._meta.resource_name,
self.get_packages,
name='api_grid_packages',
),
]
def get_packages(self, request, **kwargs):
"""
Returns a serialized list of resources based on the identifiers
from the URL.
Pulls the data from the model :class:`~apps.package.models.Package`.
Calls ``obj_get`` to fetch only the objects requested. This method
only responds to HTTP GET.
Should return a ``HttpResponse`` (200 OK).
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
qs = Package.objects.filter(grid__slug=kwargs['grid_name'])
pkg = PackageResource()
object_list = [pkg.full_dehydrate(obj) for obj in qs]
self.log_throttled_access(request)
return self.create_response(request, object_list)
class DpotwResource(ModelResource):
"""Package of the week resource.
Pulls data from :class:`~apps.homepage.models.Dpotw`.
"""
class Meta:
queryset = Dpotw.objects.all()
resource_name = 'package-of-the-week'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'package__slug'
excludes = ["id"]
class GotwResource(EnhancedModelResource):
"""Grid of the week resource.
The data comes from :class:`~apps.homepage.models.GotwResource`
"""
class Meta:
queryset = Gotw.objects.all()
resource_name = 'grid-of-the-week'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'grid__slug'
excludes = ["id"]
class CategoryResource(EnhancedModelResource):
"""Category resource.
The data is from :class:`~apps.package.models.Category`.
"""
class Meta:
queryset = Category.objects.all()
resource_name = 'category'
allowed_methods = ['get']
lookup_field = 'slug'
excludes = ["id"]
class UserResource(EnhancedModelResource):
"""User resource.
The data is from the :class:`contrib.auth.models.User`.
Exposes ``last_login``, ``username`` and ``date_joined``.
"""
class Meta:
queryset = User.objects.all().order_by("-id")
resource_name = 'user'
allowed_methods = ['get']
lookup_field = 'username'
fields = ["resource_uri", "last_login", "username", "date_joined"]
class PackageResource(PackageResourceBase):
"""Package resource.
Pulls data from :class:`~apps.package.models.Package` and provides
additional related data:
* :attr:`category`
* :attr:`grids`
* :attr:`created_by`
* :attr:`last_modified_by`
* :attr:`pypi_vesion`
"""
category = fields.ForeignKey(CategoryResource, "category")
grids = fields.ToManyField(GridResource, "grid_set")
created_by = fields.ForeignKey(UserResource, "created_by", null=True)
last_modified_by = fields.ForeignKey(UserResource, "created_by", null=True)
pypi_version = fields.CharField('pypi_version')
commits_over_52 = fields.CharField('commits_over_52')
usage_count = fields.CharField('get_usage_count')
class Meta:
queryset = Package.objects.all()
resource_name = 'package'
allowed_methods = ['get']
include_absolute_url = True
lookup_field = 'slug'
| {
"repo_name": "benracine/opencomparison",
"path": "apps/apiv1/resources.py",
"copies": "3",
"size": "6773",
"license": "mit",
"hash": 8039232565187080000,
"line_mean": 31.2523809524,
"line_max": 91,
"alpha_frac": 0.6115458438,
"autogenerated": false,
"ratio": 4.112325440194293,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.013784750535862537,
"num_lines": 210
} |
# api/resources/bucketlist.py
import datetime
from flask import request, jsonify, g, make_response, current_app
from sqlalchemy.exc import SQLAlchemyError
from common.authentication import AuthRequiredResource
from api.models import BucketList, BucketItem, db
from api.schemas import BucketItemSchema, BucketListSchema
from common.utils import PaginateData
buckets_schema = BucketListSchema()
bucketitem_schema = BucketItemSchema()
class ResourceBucketLists(AuthRequiredResource):
# get all bucketlists for the user
def get(self):
search_term = request.args.get('q')
if search_term:
search_results = BucketList.query.filter_by(
created_by=g.user.id).filter(
BucketList.name.ilike('%' + search_term + '%'))
get_data_query = search_results
else:
get_data_query = BucketList.query.filter_by(created_by=g.user.id)
paginate_content = PaginateData(
request,
query=get_data_query,
resource_for_url='api_v1.bucket_lists',
key_name='results',
schema=buckets_schema
)
paginated_data = paginate_content.paginate_query()
if paginated_data['results']:
return paginated_data, 200
else:
response = {'Results': 'No Resource found'}
return response, 404
# create a bucketlist for the user
def post(self):
request_data = request.get_json()
if not request_data:
response = {'Bucketlist': 'No input data provided'}
return response, 400
errors = buckets_schema.validate(request_data)
if errors:
return errors, 403
try:
bucket_name = request_data['name']
exists = BucketList.query.filter_by(created_by=g.user.id, name=bucket_name).first()
if not exists:
bucketlist = BucketList()
bucketlist.name = bucket_name
bucketlist.created_by = g.user.id
bucketlist.add(bucketlist)
response_data = BucketList.query.filter_by(created_by=g.user.id, name=bucket_name).first()
response = buckets_schema.dump(response_data).data
return response, 201
else:
response = {'Error': '{} already exists!'.format(bucket_name)}
return response, 409
except SQLAlchemyError:
db.session.rollback()
response = {'error': 'Resource could not be created'}
return response, 401
class ResourceBucketList(AuthRequiredResource):
def get(self, id):
# return all bucketlists with their items for the user
# return a specific bucketlist with its items for the user
bucket = BucketList.query.get(id)
if not bucket:
response = {'Error': 'Resource not found'}
return response, 404
response = buckets_schema.dump(bucket).data
return response, 200
def put(self, id):
# edit a bucketlist
bucket = BucketList.query.get(id)
if not bucket:
response = {'Error': 'Resource does not exist'}
return response, 404
bucket_request = request.get_json(force=True)
if 'name' in bucket_request:
bucket.name = bucket_request['name']
bucket.date_modified = datetime.datetime.now()
dumped_message, dump_errors = buckets_schema.dump(bucket)
if dump_errors:
return dump_errors, 400
validate_error = buckets_schema.validate(dumped_message)
if validate_error:
return validate_error, 400
try:
bucket.update()
return self.get(id)
except SQLAlchemyError:
db.session.rollback()
response = {'Error': 'Could not update'}
return response, 400
def delete(self, id):
# delete a bucketlist
bucket = BucketList.query.get(id)
if not bucket:
response = {'Error': 'Resource does not exist!'}
return response, 404
try:
bucket.delete(bucket)
response = {'Status': 'Delete operation successful'}
return response, 204
except SQLAlchemyError:
db.session.rollback()
response = {"error": "Error Deleting Object"}
return response, 500
class ResourceBucketItems(AuthRequiredResource):
# create a new item, in bucketlist
def post(self, id):
request_data = request.get_json()
if not request_data:
response = {'Error': 'No input data not provided'}
return response, 400
errors = bucketitem_schema.validate(request_data)
if errors:
return errors, 403
try:
bucket_item_name = request_data['name']
exists = BucketItem.query.filter_by(bucket_id=id, name=bucket_item_name).first()
if not exists:
bucket_item = BucketItem()
bucket_item.name = request_data['name']
bucket_item.bucket_id = id
bucket_item.add(bucket_item)
response_data = BucketItem.query.filter_by(bucket_id=id, name=bucket_item_name).first()
response = bucketitem_schema.dump(response_data).data
return response, 201
else:
response = {'Error': '{} already exists!'.format(bucket_item_name)}
return response, 409
except SQLAlchemyError:
db.session.rollback()
response = {'error': 'Could not create resource'}
return response, 401
# get all bucket items
def get(self, id):
bucket_items_query = BucketItem.query.filter_by(bucket_id=id)
if not bucket_items_query.count():
response = {'Error': 'Resource not found'}
return response, 404
bucketitems = bucketitem_schema.dump(bucket_items_query, many=True).data
return bucketitems, 200
class ResourceBucketItem(AuthRequiredResource):
# get a single bucket item
def get(self, id, item_id):
bucket = BucketItem.query.get(item_id)
if not bucket:
response = {'Error': 'Resource not found'}
return response, 404
response = bucketitem_schema.dump(bucket).data
return response, 200
def put(self, id, item_id):
# Update a bucket list item
bucket_item = BucketItem.query.get(item_id)
if not bucket_item:
response = {'Error': 'Resource not found'}
return response, 404
bucket_item_request = request.get_json(force=True)
if not bucket_item_request:
response = {'Error': 'Nothing to update'}
return response, 412
else:
if 'name' in bucket_item_request:
bucket_item.name = bucket_item_request['name']
if 'done' in bucket_item_request:
bucket_item.done = bucket_item_request['done']
bucket_item.date_modified = datetime.datetime.now()
dumped_message, dump_errors = bucketitem_schema.dump(bucket_item)
if dump_errors:
return dump_errors, 400
validate_error = bucketitem_schema.validate(dumped_message)
if validate_error:
return validate_error, 400
try:
bucket_item.update()
return self.get(id, item_id)
except SQLAlchemyError:
db.session.rollback()
response = {"error": "Resource could not be updated"}
return response, 400
def delete(self, id, item_id):
# Delete a bucketlist item
bucket_item = BucketItem.query.get(item_id)
if not bucket_item:
response = {'Error': 'Resource not found'}
return response, 404
try:
bucket_item.delete(bucket_item)
response = {'Status': 'Delete operation successful'}
return response, 204
except SQLAlchemyError:
db.session.rollback()
response = {"error": "Could not delete resource"}
return response, 401
| {
"repo_name": "Mbarak-Mbigo/cp2_bucketlist",
"path": "api/resources/bucketlist.py",
"copies": "1",
"size": "8312",
"license": "mit",
"hash": 8987224610170460000,
"line_mean": 37.128440367,
"line_max": 106,
"alpha_frac": 0.5826515881,
"autogenerated": false,
"ratio": 4.435432230522945,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5518083818622945,
"avg_score": null,
"num_lines": null
} |
"""API resources"""
from __future__ import absolute_import
from builtins import object
import logging
import json
import redis
from django.contrib.auth.models import User
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.core.cache import cache
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.constants import ALL_WITH_RELATIONS, ALL
from tastypie.resources import ModelResource
from tastypie.http import HttpCreated, HttpApplicationError
from tastypie.utils import dict_strip_unicode_keys, trailing_slash
from readthedocs.builds.constants import LATEST
from readthedocs.builds.models import Version
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project, ImportedFile
from .utils import SearchMixin, PostAuthentication
log = logging.getLogger(__name__)
class ProjectResource(ModelResource, SearchMixin):
"""API resource for Project model."""
users = fields.ToManyField('readthedocs.api.base.UserResource', 'users')
class Meta(object):
include_absolute_url = True
allowed_methods = ['get', 'post', 'put']
queryset = Project.objects.api()
authentication = PostAuthentication()
authorization = DjangoAuthorization()
excludes = ['path', 'featured', 'programming_language']
filtering = {
"users": ALL_WITH_RELATIONS,
"slug": ALL_WITH_RELATIONS,
}
def get_object_list(self, request):
self._meta.queryset = Project.objects.api(user=request.user)
return super(ProjectResource, self).get_object_list(request)
def dehydrate(self, bundle):
bundle.data['downloads'] = bundle.obj.get_downloads()
return bundle
def post_list(self, request, **kwargs):
"""
Creates a new resource/object with the provided data.
Calls ``obj_create`` with the provided data and returns a response
with the new resource's location.
If a new resource is created, return ``HttpCreated`` (201 Created).
"""
deserialized = self.deserialize(
request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json')
)
# Force this in an ugly way, at least should do "reverse"
deserialized["users"] = ["/api/v1/user/%s/" % request.user.id]
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)
self.is_valid(bundle)
updated_bundle = self.obj_create(bundle, request=request)
return HttpCreated(location=self.get_resource_uri(updated_bundle))
def sync_versions(self, request, **kwargs):
"""
Sync the version data in the repo (on the build server) with what we have in the database.
Returns the identifiers for the versions that have been deleted.
"""
project = get_object_or_404(Project, pk=kwargs['pk'])
try:
post_data = self.deserialize(
request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json')
)
data = json.loads(post_data)
self.method_check(request, allowed=['post'])
self.is_authenticated(request)
self.throttle_check(request)
self.log_throttled_access(request)
self._sync_versions(project, data['tags'])
self._sync_versions(project, data['branches'])
deleted_versions = self._delete_versions(project, data)
except Exception as e:
return self.create_response(
request,
{'exception': str(e)},
response_class=HttpApplicationError,
)
return self.create_response(request, deleted_versions)
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/schema/$" % self._meta.resource_name,
self.wrap_view('get_schema'), name="api_get_schema"),
url(r"^(?P<resource_name>%s)/search%s$" % (
self._meta.resource_name, trailing_slash()),
self.wrap_view('get_search'), name="api_get_search"),
url(r"^(?P<resource_name>%s)/(?P<pk>\d+)/sync_versions%s$" % (
self._meta.resource_name, trailing_slash()),
self.wrap_view('sync_versions'), name="api_sync_versions"),
url((r"^(?P<resource_name>%s)/(?P<slug>[a-z-_]+)/$")
% self._meta.resource_name, self.wrap_view('dispatch_detail'),
name="api_dispatch_detail"),
]
class VersionResource(ModelResource):
"""API resource for Version model."""
project = fields.ForeignKey(ProjectResource, 'project', full=True)
class Meta(object):
allowed_methods = ['get', 'put', 'post']
always_return_data = True
queryset = Version.objects.api()
authentication = PostAuthentication()
authorization = DjangoAuthorization()
filtering = {
"project": ALL_WITH_RELATIONS,
"slug": ALL_WITH_RELATIONS,
"active": ALL,
}
def get_object_list(self, request):
self._meta.queryset = Version.objects.api(user=request.user)
return super(VersionResource, self).get_object_list(request)
def build_version(self, request, **kwargs):
project = get_object_or_404(Project, slug=kwargs['project_slug'])
version = kwargs.get('version_slug', LATEST)
version_obj = project.versions.get(slug=version)
trigger_build(project=project, version=version_obj)
return self.create_response(request, {'building': True})
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/schema/$"
% self._meta.resource_name,
self.wrap_view('get_schema'),
name="api_get_schema"),
url(r"^(?P<resource_name>%s)/(?P<project__slug>[a-z-_]+[a-z0-9-_]+)/$" # noqa
% self._meta.resource_name,
self.wrap_view('dispatch_list'),
name="api_version_list"),
url((r"^(?P<resource_name>%s)/(?P<project_slug>[a-z-_]+[a-z0-9-_]+)/(?P"
r"<version_slug>[a-z0-9-_.]+)/build/$")
% self._meta.resource_name,
self.wrap_view('build_version'),
name="api_version_build_slug"),
]
class FileResource(ModelResource, SearchMixin):
"""API resource for ImportedFile model."""
project = fields.ForeignKey(ProjectResource, 'project', full=True)
class Meta(object):
allowed_methods = ['get', 'post']
queryset = ImportedFile.objects.all()
excludes = ['md5', 'slug']
include_absolute_url = True
authentication = PostAuthentication()
authorization = DjangoAuthorization()
search_facets = ['project']
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/schema/$" %
self._meta.resource_name,
self.wrap_view('get_schema'),
name="api_get_schema"),
url(r"^(?P<resource_name>%s)/search%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('get_search'),
name="api_get_search"),
url(r"^(?P<resource_name>%s)/anchor%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('get_anchor'),
name="api_get_anchor"),
]
def get_anchor(self, request, **__):
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
query = request.GET.get('q', '')
try:
redis_client = cache.get_client(None)
redis_data = redis_client.keys("*redirects:v4*%s*" % query)
except (AttributeError, redis.exceptions.ConnectionError):
redis_data = []
# -2 because http:
urls = [''.join(data.split(':')[6:]) for data in redis_data
if 'http://' in data]
object_list = {'objects': urls}
self.log_throttled_access(request)
return self.create_response(request, object_list)
class UserResource(ModelResource):
"""Read-only API resource for User model."""
class Meta(object):
allowed_methods = ['get']
queryset = User.objects.all()
fields = ['username', 'first_name', 'last_name', 'last_login', 'id']
filtering = {
'username': 'exact',
}
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/schema/$" %
self._meta.resource_name,
self.wrap_view('get_schema'),
name="api_get_schema"),
url(r"^(?P<resource_name>%s)/(?P<username>[a-z-_]+)/$" %
self._meta.resource_name,
self.wrap_view('dispatch_detail'),
name="api_dispatch_detail"),
]
| {
"repo_name": "pombredanne/readthedocs.org",
"path": "readthedocs/api/base.py",
"copies": "1",
"size": "9069",
"license": "mit",
"hash": 8585775235340363000,
"line_mean": 36.6307053942,
"line_max": 98,
"alpha_frac": 0.5911346345,
"autogenerated": false,
"ratio": 4.036048064085447,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00013395179522833904,
"num_lines": 241
} |
"API resource templates. To be used with django-preserialize."
from copy import deepcopy
# Since this is a Lexicon subclass, the `label` is only used and merged
# into the parent object.
Chromosome = {
'fields': ['chr'],
'aliases': {
'chr': 'label',
},
'merge': True,
}
# Flat list of PubMed articles. This can be used with Gene, Phenotype, or
# Variant
Article = {
'fields': ['pmid'],
'values_list': True,
}
# Phenotype representation
Phenotype = {
'related': {
'articles': Article,
}
}
# Reference phenotype with minimal information
PhenotypeList = {
'fields': ['term'],
'values_list': True,
}
VariantPhenotype = {
'exclude': ['variant'],
'related': {
'phenotype': {
'fields': ['term', 'hpo_id'],
'merge': True,
}
}
}
PhenotypeSearch = {
'fields': [':pk', 'term', 'description'],
}
GeneFamily = {
'fields': ['description'],
'values_list': True,
}
# Flat list of gene synonyms. This must be used in the context of a Gene
GeneSynonym = {
'fields': ['label'],
'values_list': True,
}
GeneTranscript = {
'fields': ['transcript'],
'aliases': {
'transcript': 'refseq_id',
},
'values_list': True,
}
# Detailed gene information
Gene = {
'related': {
'chr': Chromosome,
'synonyms': GeneSynonym,
'transcripts': GeneTranscript,
'families': GeneFamily,
'articles': Article,
'phenotypes': PhenotypeList,
}
}
# Minimal information for the gene search
GeneSearch = {
'fields': [':pk', 'symbol', 'name', 'synonyms', 'approved'],
'related': {
'synonyms': {
'fields': ['label'],
'values_list': True,
}
}
}
# Limited gene information to be embedded in a Transcript
TranscriptGene = {
'exclude': ['synonyms', 'transcripts', 'chr', 'families', 'id', 'name'],
'related': {
'chr': Chromosome,
'articles': Article,
}
}
# This version of the resource includes the gene this transcript represents
Transcript = {
'fields': ['transcript', 'gene'],
'aliases': {
'transcript': 'refseq_id',
},
'related': {
'gene': TranscriptGene,
},
}
# Lexicon of types of variants, only the `label` must be used here. This
# is only ever used in the context of a variant, so the name `type` is
# suitable.
VariantType = {
'fields': ['type'],
'aliases': {
'type': 'label',
},
'merge': True,
}
# SIFT deleterious prediction and raw score
Sift = {
'fields': ['score', 'prediction'],
}
# PolyPhen2 deleterious prediction and raw score
PolyPhen2 = {
'fields': ['score', 'prediction'],
}
# Allele frequencies for various races. This must be used in the context
# of a Variant
ThousandG = {
'fields': ['all_af', 'amr_af', 'afr_af', 'asn_af', 'eur_af'],
'aliases': {
'all_af': 'af',
}
}
# Allele frequencies for various races. This must be used in the context
# of a Variant
Evs = {
'fields': ['all_af', 'afr_af', 'eur_af', 'read_depth'],
'aliases': {
'eur_af': 'ea_af',
'afr_af': 'aa_af',
}
}
# Lexicon, only use the label
EffectRegion = {
'fields': ['region'],
'aliases': {
'region': 'label',
},
'merge': True,
}
# Lexicon, only use the label
EffectImpact = {
'fields': ['impact'],
'aliases': {
'impact': 'label',
},
'merge': True,
}
# Extended lexicon, who other properties about the effect type
Effect = {
'fields': ['type', 'impact'],
'aliases': {
'type': 'label',
},
'related': {
'impact': EffectImpact,
'region': EffectRegion,
},
'merge': True,
}
# The variant effect has quite a few components. Since it does not include
# Variant, it is assumed to be used in the context of a Variant
VariantEffect = {
'fields': ['transcript', 'amino_acid_change', 'effect', 'hgvs_c',
'hgvs_p', 'segment'],
'related': {
'transcript': Transcript,
'functional_class': {
'fields': ['functional_class'],
'aliases': {
'functional_class': 'label',
},
'merge': True,
},
'effect': Effect
}
}
# Represents the simplest representation of a Sample, that is, the primary key
# and the Sample name.
SimpleSample = {
'fields': [':pk', 'name'],
}
# Used to augment the variant resource below. This is separate to
# be able to restrict cohorts for the requesting user
CohortVariant = {
'fields': ['af', 'cohort'],
'related': {
'cohort': {
'fields': ['name', 'size'],
'aliases': {
'size': 'count',
},
'merge': True,
}
}
}
# Detailed resource for a variant, this should only be used when requesting
# one or a few variants at time (meaning don't pull down 1000).
Variant = {
'fields': [':pk', 'chr', 'pos', 'ref', 'alt', 'rsid', 'type',
'effects', '1000g', 'sift', 'evs', 'polyphen2', 'articles',
'phenotypes'],
# Map to cleaner names
'aliases': {
'1000g': 'thousandg',
'phenotypes': 'variant_phenotypes',
},
'related': {
'type': VariantType,
'chr': Chromosome,
'sift': Sift,
'thousandg': ThousandG,
'evs': Evs,
'polyphen2': PolyPhen2,
'effects': VariantEffect,
'articles': Article,
'variant_phenotypes': VariantPhenotype,
'cohort_details': CohortVariant,
}
}
# Project
# Exposes the label
Project = {
'fields': ['project'],
'merge': True,
'aliases': {
'project': 'label',
},
}
# Batch
# Exposes the batch and project names and size
Batch = {
'fields': ['batch'],
'merge': True,
'aliases': {
'batch': 'label',
},
}
# Sample Resource
# project and batch names are merged into the sample object to
# remove excessive nesting.
Sample = {
'fields': [':pk', 'batch', 'count', 'created', 'label', 'project'],
'related': {
'batch': Batch,
'project': Project,
}
}
ResultVariant = {
'fields': ['variant_id', 'chr', 'pos', 'ref', 'alt'],
'aliases': {
'variant_id': 'id',
},
'related': {
'chr': Chromosome,
},
'merge': True,
}
Genotype = {
'fields': ['genotype', 'genotype_description'],
'aliases': {
'genotype': 'value',
'genotype_description': 'label',
},
'merge': True,
}
Assessment = {
'exclude': ['user', 'sample_result', 'notes']
}
ResultAssessment = {
'fields': ['id', 'assessment_category', 'pathogenicity']
}
SampleResult = {
'fields': [':pk', ':local', 'genotype_value', 'read_depth_ref',
'read_depth_alt', 'base_counts'],
'exclude': ['created', 'modified', 'downsampling', 'fisher_strand',
'homopolymer_run', 'notes', 'spanning_deletions',
'strand_bias', 'mq', 'mq0', 'mq_rank_sum',
'phred_scaled_likelihood', 'read_pos_rank_sum', 'in_dbsnp',
'coverage_ref', 'coverage_alt'],
'aliases': {
'base_counts': 'base_count_map',
'read_depth_alt': 'coverage_alt',
'read_depth_ref': 'coverage_ref',
},
'related': {
'variant': ResultVariant,
'sample': Sample,
'genotype': Genotype,
}
}
# This is deviation of the normal SampleResult which only includes
# the variant_id. This is used downstreamed to simply link together
# data from an alternate source.
SampleResultVariant = deepcopy(SampleResult)
SampleResultVariant['related']['variant'] = {
'fields': ['variant_id'],
'aliases': {
'variant_id': 'id',
},
'merge': True,
}
SimpleResultSet = {
'fields': [':local', 'created', 'modified'],
'exclude': ['user', 'results'],
'related': {
'sample': Sample
}
}
ResultSet = {
'fields': [':local', 'created', 'modified'],
'related': {
'sample': Sample,
'results': SampleResult
}
}
| {
"repo_name": "chop-dbhi/varify",
"path": "varify/api/templates.py",
"copies": "1",
"size": "8094",
"license": "bsd-2-clause",
"hash": 7723360675809313000,
"line_mean": 20.8167115903,
"line_max": 78,
"alpha_frac": 0.5495428713,
"autogenerated": false,
"ratio": 3.4195183776932825,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9469061248993282,
"avg_score": 0,
"num_lines": 371
} |
"""API routes for locations."""
from flask import jsonify, request
from werkzeug.exceptions import NotFound
from ceraon.constants import Errors
from ceraon.models.locations import Location
from ceraon.utils import RESTBlueprint
from .schema import LocationSchema
blueprint = RESTBlueprint('locations', __name__, version='v1')
LOCATION_SCHEMA = LocationSchema(exclude=LocationSchema.private_fields)
@blueprint.find()
def find_location(uid):
"""Find a location given the uuid.
---
tags:
- locations
definitions:
- schema:
id: Location
properties:
id:
type: string
description: the ID of the location
address:
type: string
description: the full address of the location
latitude:
type: number
format: Float
description: the latitude of the location
longitude:
type: number
format: Float
description: the longitude of the location
parameters:
- in: path
name: uid
required: true
description: the UUID of the location
responses:
200:
description: Location data found
schema:
id: Locations
404:
description: The location could not be found
"""
location = Location.find(uid)
if location is None:
raise NotFound(Errors.LOCATION_NOT_FOUND)
return jsonify(data=LOCATION_SCHEMA.dump(location).data)
@blueprint.list()
def list_locations():
"""List the locations.
---
tags:
- locations
parameters:
- in: query
name: page
description: the page of the meals to retrieve
default: 1
- in: query
name: per_page
description: the number of results to return per page
default: 10
- in: query
name: source
description: the source of the location. Use "internal" for locations
created by users
responses:
200:
description: Location data found
schema:
type: array
items:
schema:
id: Locations
"""
if request.args.get('source') is not None:
source = request.args.get('source')
if source == 'internal':
source = None
filtered = Location.query.filter(Location.source == source)
else:
filtered = Location.query
page = filtered.paginate(page=int(request.args.get('page', 1)),
per_page=int(request.args.get('per_page', 10)))
meta_pagination = {
'first': request.path + '?page={page}&per_page={per_page}'.format(
page=1, per_page=page.per_page),
'next': request.path + '?page={page}&per_page={per_page}'.format(
page=page.next_num, per_page=page.per_page),
'last': request.path + '?page={page}&per_page={per_page}'.format(
page=page.pages or 1, per_page=page.per_page),
'prev': request.path + '?page={page}&per_page={per_page}'.format(
page=page.prev_num, per_page=page.per_page),
'total': page.pages
}
if not page.has_next:
meta_pagination.pop('next')
if not page.has_prev:
meta_pagination.pop('prev')
return jsonify(data=LOCATION_SCHEMA.dump(page.items, many=True).data,
meta={'pagination': meta_pagination})
| {
"repo_name": "Rdbaker/Mealbound",
"path": "ceraon/api/v1/locations/views.py",
"copies": "1",
"size": "3391",
"license": "bsd-3-clause",
"hash": 1580708058988864800,
"line_mean": 27.7372881356,
"line_max": 76,
"alpha_frac": 0.5962842819,
"autogenerated": false,
"ratio": 4.217661691542289,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5313945973442289,
"avg_score": null,
"num_lines": null
} |
"""API routes for users."""
from flask import jsonify, request
from flask_login import current_user, login_required
from ceraon.constants import Errors, Success
from ceraon.errors import BadRequest, NotFound, TransactionVendorError
from ceraon.models.transactions import Transaction
from ceraon.user.models import User
from ceraon.utils import RESTBlueprint
from .schema import UserSchema
blueprint = RESTBlueprint('users', __name__, version='v1')
USER_SCHEMA = UserSchema(only=('created_at', 'public_name', 'image_url', 'id'))
PRIVATE_USER_SCHEMA = UserSchema()
@blueprint.flexible_route('/me', methods=['GET'])
@login_required
def get_me():
"""
Get the logged in user.
---
tags:
- users
definitions:
- schema:
id: User
properties:
id:
type: integer
description: the user's ID
created_at:
type: dateTime
description: ISO-8601 date string for when the user was created
public_name:
type: string
description: the name to display in the app
first_name:
type: string
description: the first name of the user
last_name:
type: string
description: the last name of the user
image_url:
type: string
description: the URL of the user's profile photo
email:
type: string
description: the email of the user (private)
address:
type: string
description: the address of the user's location (private)
responses:
200:
description: User data found
schema:
id: User
401:
description: The user is not authenticated
"""
return jsonify(data=PRIVATE_USER_SCHEMA.dump(current_user).data)
@blueprint.flexible_route('/me/payment-info', methods=['POST', 'PUT', 'PATCH'])
@login_required
def update_my_payment_info():
"""Update the currently logged-in user's payment info.
Since we use stripe, this will currently update the users's
stripe_customer_id
---
tags:
- users
parameters:
- in: body
name: body
schema:
properties:
stripe_token:
type: string
description: the token returned from strip for payment info
responses:
200:
description: User payment info updated
400:
description: No stripe_token was supplied
500:
description: Something went wront when talking to stripe
"""
token = request.json.get('stripe_token')
if not token:
raise BadRequest(Errors.STRIPE_TOKEN_REQUIRED)
if not Transaction.set_stripe_source_on_user(current_user, token):
raise TransactionVendorError(Errors.TRANSACTION_VENDOR_CONTACT_FAILED)
return jsonify(data=None, message=Success.PAYMENT_INFO_UPDATED), 200
@blueprint.flexible_route('/me', methods=['PATCH'])
@login_required
def update_me():
"""
Update data for the currently logged in user.
---
tags:
- users
parameters:
- in: body
name: body
schema:
id: User
properties:
address:
type: string
description: the address for the user's location
first_name:
type: string
last_name:
type: string
email:
type: string
password:
type: string
confirm_pw:
type: string
description: the confirmation for the user's new password
responses:
200:
description: User data updated
schema:
id: User
400:
description: The password and confirm_pw didn't match
401:
description: The user is not authenticated
422:
description: The data did not pass validation
"""
user_data = PRIVATE_USER_SCHEMA.load(request.json, partial=True).data
if 'password' in request.json:
if request.json.get('password') != request.json.get('confirm_pw'):
raise BadRequest(Errors.PASSWORD_CONFIRM_MATCH)
else:
current_user.set_password(request.json.get('password'))
current_user.update(**user_data)
return jsonify(data=PRIVATE_USER_SCHEMA.dump(current_user).data,
message=Success.PROFILE_UPDATED), 200
@blueprint.find()
def find_user(uid):
"""
Find the user specified by the ID.
---
tags:
- users
parameters:
- in: path
name: uid
description: The user's id
required: true
responses:
200:
description: User data found
schema:
id: User
404:
description: The user could not be found
"""
user = User.find(uid)
if user is None:
raise NotFound(Errors.USER_NOT_FOUND)
return jsonify(data=USER_SCHEMA.dump(user).data)
| {
"repo_name": "Rdbaker/Mealbound",
"path": "ceraon/api/v1/users/api.py",
"copies": "1",
"size": "5024",
"license": "bsd-3-clause",
"hash": 961367607746053400,
"line_mean": 27.2247191011,
"line_max": 79,
"alpha_frac": 0.5929538217,
"autogenerated": false,
"ratio": 4.426431718061674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5519385539761674,
"avg_score": null,
"num_lines": null
} |
# api/schemas.py
from marshmallow import Schema, fields, pre_load
from marshmallow import validate, validates_schema, ValidationError
from flask_marshmallow import Marshmallow
ma = Marshmallow()
# Schemas do validate, serialize and deserialize models
class UserSchema(ma.Schema):
id = fields.Integer(dump_only=True)
username = fields.String(validate=(validate.Length(min=1, error='Username Required')))
password = fields.String(validate=validate.Length(min=1, error='Password Required'))
email = fields.String(validate=(validate.Length(min=1, error='Email Required'),
validate.Email(error='Invalid Email address')))
created_date = fields.DateTime()
class BucketListSchema(ma.Schema):
id = fields.Integer(dump_only=True)
name = fields.String(validate=validate.Length(min=1, error='Bucketlist Name Required'))
date_created = fields.DateTime()
date_modified = fields.DateTime()
user = fields.Nested('UserSchema', only=['id', 'username'])
items = fields.Nested('BucketItemSchema', many=True, exclude=('bucketlist',))
url = ma.UrlFor('api_v1.bucket_list', id='<id>', _external=True)
class BucketItemSchema(ma.Schema):
id = fields.Integer(dump_only=True)
name = fields.String(validate=validate.Length(min=1, error='Bucketitem Name Required'))
done = fields.Boolean(default=False)
date_created = fields.DateTime()
date_modified = fields.DateTime()
bucketlist = fields.Nested('BucketListSchema', only=['id', 'name'])
url = ma.UrlFor('api_v1.bucket_item', id='<bucket_id>', item_id='<id>', _external=True)
| {
"repo_name": "Mbarak-Mbigo/cp2_bucketlist",
"path": "api/schemas.py",
"copies": "1",
"size": "1617",
"license": "mit",
"hash": 9173479755238730000,
"line_mean": 42.7027027027,
"line_max": 91,
"alpha_frac": 0.7043908472,
"autogenerated": false,
"ratio": 3.7002288329519453,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9892344233198147,
"avg_score": 0.0024550893907596756,
"num_lines": 37
} |
"""API SDK"""
# coding:utf-8
import requests
AUTH = ('api', 'api123')
URL = 'https://api.iloft.xyz/'
HEADERS = {'content-type': 'application/json'}
def get_status(type_id, device_id):
"""Get Device Status"""
if type_id == 0:
g_controller = requests.get(
url=URL + 'controller/' + str(device_id), auth=AUTH)
controller_data = g_controller.json()
return controller_data['status']
elif type_id == 1:
g_sensor = requests.get(url=URL + 'sensor/' +
str(device_id), auth=AUTH)
sensor_data = g_sensor.json()
return sensor_data['status']
def patch_status(type_id, device_id, status):
"""Edit Device Status"""
if type_id == 0:
p_status = requests.patch(url=URL + 'controller/' + str(device_id),
data='{"status": ' + str(status) + '}', headers=HEADERS, auth=AUTH
)
return p_status.status_code
elif type_id == 1:
p_status = requests.patch(url=URL + 'sensor/' + str(device_id),
data='{"status": ' + str(status) + '}', headers=HEADERS, auth=AUTH
)
return p_status.status_code
def create_device(type_id, name, status):
"""Create New device"""
if type_id == 0:
c_device = requests.post(url=URL + 'controller/', data='{"name":' + '"' + str(
name) + '"' + ',' + '"status":' + str(status) + '}', headers=HEADERS, auth=AUTH)
if c_device.status_code == 201:
device_data = c_device.json()
return device_data['id']
else:
print("创建失败,请检查是否有重名设备")
if type_id == 1:
c_device = requests.post(url=URL + 'sensor/', data='{"name":' + '"' + str(
name) + '"' + ',' + '"status":' + str(status) + '}', headers=HEADERS, auth=AUTH)
if c_device.status_code == 201:
device_data = c_device.json()
return device_data['id']
else:
print("创建失败,请检查是否有重名设备")
def delete_device(type_id, device_id):
"""Delete Device"""
if type_id == 0:
d_device = requests.delete(
url=URL + 'controller/' + str(device_id), headers=HEADERS, auth=AUTH)
return d_device.status_code
if type_id == 1:
d_device = requests.delete(
url=URL + 'sensor/' + str(device_id), headers=HEADERS, auth=AUTH)
return d_device.status_code
| {
"repo_name": "myloft/API-SDK",
"path": "api.py",
"copies": "1",
"size": "2527",
"license": "mit",
"hash": -9140694339509182000,
"line_mean": 35.3382352941,
"line_max": 100,
"alpha_frac": 0.5224605423,
"autogenerated": false,
"ratio": 3.4035812672176307,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9416175060894041,
"avg_score": 0.0019733497247180886,
"num_lines": 68
} |
"""API section, including all REST views."""
from __future__ import absolute_import
from flask import Blueprint, jsonify, request
from scanlation_cms.extensions import cache
from scanlation_cms.panel.models import News, Thanks
from scanlation_cms.utils import get_object_or_404, get_or_create
blueprint = Blueprint(
'api',
__name__,
url_prefix='/api/v1',
static_folder='../static'
)
@blueprint.route('/hello', methods=['GET'])
def hello():
"""Sample hello function."""
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
return jsonify({'Hello': ip})
@blueprint.route('/thanks', methods=['POST'])
def thanks():
"""Function for creating new Thanks obj."""
if request.method == 'POST':
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
news_id = int(request.get_data())
msg = ''
news = get_object_or_404(News, News.id == news_id)
new_thanks, created = get_or_create(Thanks, ip=ip, news_id=news.id)
if not created:
response = 'already_voted'
else:
response = 'successfully_voted'
msg = news.thanks_counter
cache.delete('home')
return jsonify({'response': response, 'msg': msg})
| {
"repo_name": "dyzajash/scanlation_cms",
"path": "scanlation_cms/api/views.py",
"copies": "1",
"size": "1434",
"license": "bsd-3-clause",
"hash": 5804927955651973000,
"line_mean": 30.1739130435,
"line_max": 75,
"alpha_frac": 0.619944212,
"autogenerated": false,
"ratio": 3.6581632653061225,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9778107477306123,
"avg_score": 0,
"num_lines": 46
} |
"""API serializers."""
from rest_framework import serializers
from modoboa.admin import models as admin_models
from . import models
class EmailProviderDomainSerializer(serializers.ModelSerializer):
"""Serializer class for EmailProviderDomain."""
id = serializers.IntegerField(required=False)
class Meta:
extra_kwargs = {
"name": {
"validators": []
}
}
fields = ("id", "name", "new_domain")
model = models.EmailProviderDomain
class EmailProviderSerializer(serializers.ModelSerializer):
"""Serializer class for EmailProvider."""
domains = EmailProviderDomainSerializer(many=True, required=False)
class Meta:
fields = "__all__"
model = models.EmailProvider
def create(self, validated_data):
"""Create provider and domains."""
domains = validated_data.pop("domains", None)
validated_data.pop("id", None)
provider = models.EmailProvider.objects.create(**validated_data)
if domains:
to_create = []
for domain in domains:
to_create.append(models.EmailProviderDomain(
provider=provider, **domain))
models.EmailProviderDomain.objects.bulk_create(to_create)
return provider
def update(self, instance, validated_data):
"""Update provider and domains."""
domains = validated_data.pop("domains", [])
domain_ids = [domain["id"] for domain in domains if "id" in domain]
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
for domain in instance.domains.all():
if domain.id not in domain_ids:
domain.delete()
else:
for updated_domain in domains:
if updated_domain.get("id") != domain.id:
continue
domain.name = updated_domain["name"]
domain.new_domain = updated_domain.get("new_domain")
domain.save()
domains.remove(updated_domain)
break
to_create = []
for new_domain in domains:
to_create.append(models.EmailProviderDomain(
name=new_domain["name"],
new_domain=new_domain.get("new_domain"),
provider=instance
))
models.EmailProviderDomain.objects.bulk_create(to_create)
return instance
class MailboxSerializer(serializers.ModelSerializer):
"""Simple mailbox serializer."""
class Meta:
fields = ("id", "full_address")
model = admin_models.Mailbox
class MigrationSerializer(serializers.ModelSerializer):
"""Serializer class for Migration."""
mailbox = MailboxSerializer()
class Meta:
depth = 1
fields = ("id", "provider", "mailbox", "username")
model = models.Migration
| {
"repo_name": "modoboa/modoboa-imap-migration",
"path": "modoboa_imap_migration/serializers.py",
"copies": "1",
"size": "2972",
"license": "isc",
"hash": -2114435977315994600,
"line_mean": 30.9569892473,
"line_max": 75,
"alpha_frac": 0.5891655451,
"autogenerated": false,
"ratio": 4.724960254372019,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 93
} |
"""APIServer tests."""
import json
import unittest
import warnings
# Disable not-grouped imports that conflicts with isort
from unittest.mock import (MagicMock, Mock, patch, # pylint: disable=C0412
sentinel)
from urllib.error import HTTPError
from kytos.core.api_server import APIServer
from kytos.core.napps import rest
KYTOS_CORE_API = "http://127.0.0.1:8181/api/kytos/"
API_URI = KYTOS_CORE_API+"core"
# pylint: disable=protected-access, too-many-public-methods
class TestAPIServer(unittest.TestCase):
"""Test the class APIServer."""
def setUp(self):
"""Instantiate a APIServer."""
self.api_server = APIServer('CustomName', False)
self.napps_manager = MagicMock()
self.api_server.server = MagicMock()
self.api_server.napps_manager = self.napps_manager
self.api_server.napps_dir = 'napps_dir'
self.api_server.flask_dir = 'flask_dir'
def test_deprecation_warning(self):
"""Deprecated method should suggest @rest decorator."""
with warnings.catch_warnings(record=True) as wrngs:
warnings.simplefilter("always") # trigger all warnings
self.api_server.register_rest_endpoint(
'rule', lambda x: x, ['POST'])
self.assertEqual(1, len(wrngs))
warning = wrngs[0]
self.assertEqual(warning.category, DeprecationWarning)
self.assertIn('@rest', str(warning.message))
def test_run(self):
"""Test run method."""
self.api_server.run()
self.api_server.server.run.assert_called_with(self.api_server.app,
self.api_server.listen,
self.api_server.port)
@patch('sys.exit')
def test_run_error(self, mock_exit):
"""Test run method to error case."""
self.api_server.server.run.side_effect = OSError
self.api_server.run()
mock_exit.assert_called()
@patch('kytos.core.api_server.request')
def test_shutdown_api(self, mock_request):
"""Test shutdown_api method."""
mock_request.host = 'localhost:8181'
self.api_server.shutdown_api()
self.api_server.server.stop.assert_called()
@patch('kytos.core.api_server.request')
def test_shutdown_api__error(self, mock_request):
"""Test shutdown_api method to error case."""
mock_request.host = 'any:port'
self.api_server.shutdown_api()
self.api_server.server.stop.assert_not_called()
def test_status_api(self):
"""Test status_api method."""
status = self.api_server.status_api()
self.assertEqual(status, ('{"response": "running"}', 200))
@patch('kytos.core.api_server.urlopen')
def test_stop_api_server(self, mock_urlopen):
"""Test stop_api_server method."""
self.api_server.stop_api_server()
url = "%s/_shutdown" % API_URI
mock_urlopen.assert_called_with(url)
@patch('kytos.core.api_server.send_file')
@patch('os.path.exists', return_value=True)
def test_static_web_ui__success(self, *args):
"""Test static_web_ui method to success case."""
(_, mock_send_file) = args
self.api_server.static_web_ui('kytos', 'napp', 'filename')
mock_send_file.assert_called_with('napps_dir/kytos/napp/ui/filename')
@patch('os.path.exists', return_value=False)
def test_static_web_ui__error(self, _):
"""Test static_web_ui method to error case."""
resp, code = self.api_server.static_web_ui('kytos', 'napp', 'filename')
self.assertEqual(resp, '')
self.assertEqual(code, 404)
@patch('kytos.core.api_server.glob')
def test_get_ui_components(self, mock_glob):
"""Test get_ui_components method."""
with self.api_server.app.app_context():
mock_glob.return_value = ['napps_dir/*/*/ui/*/*.kytos']
response = self.api_server.get_ui_components('all')
expected_json = [{'name': '*-*-*-*', 'url': 'ui/*/*/*/*.kytos'}]
self.assertEqual(response.json, expected_json)
self.assertEqual(response.status_code, 200)
@patch('os.path')
@patch('kytos.core.api_server.send_file')
def test_web_ui__success(self, mock_send_file, ospath_mock):
"""Test web_ui method."""
ospath_mock.exists.return_value = True
self.api_server.web_ui()
mock_send_file.assert_called_with('flask_dir/index.html')
@patch('os.path')
def test_web_ui__error(self, ospath_mock):
"""Test web_ui method."""
ospath_mock.exists.return_value = False
_, error = self.api_server.web_ui()
self.assertEqual(error, 404)
@patch('kytos.core.api_server.urlretrieve')
@patch('kytos.core.api_server.urlopen')
@patch('zipfile.ZipFile')
@patch('os.path.exists')
@patch('os.mkdir')
@patch('shutil.move')
def test_update_web_ui(self, *args):
"""Test update_web_ui method."""
(_, _, mock_exists, mock_zipfile, mock_urlopen,
mock_urlretrieve) = args
zipfile = MagicMock()
zipfile.testzip.return_value = None
mock_zipfile.return_value = zipfile
data = json.dumps({'tag_name': 1.0})
url_response = MagicMock()
url_response.readlines.return_value = [data]
mock_urlopen.return_value = url_response
mock_exists.side_effect = [False, True]
response = self.api_server.update_web_ui()
url = 'https://github.com/kytos/ui/releases/download/1.0/latest.zip'
mock_urlretrieve.assert_called_with(url)
self.assertEqual(response, 'updated the web ui')
@patch('kytos.core.api_server.urlretrieve')
@patch('kytos.core.api_server.urlopen')
@patch('os.path.exists')
def test_update_web_ui__http_error(self, *args):
"""Test update_web_ui method to http error case."""
(mock_exists, mock_urlopen, mock_urlretrieve) = args
data = json.dumps({'tag_name': 1.0})
url_response = MagicMock()
url_response.readlines.return_value = [data]
mock_urlopen.return_value = url_response
mock_urlretrieve.side_effect = HTTPError('url', 123, 'msg', 'hdrs',
MagicMock())
mock_exists.return_value = False
response = self.api_server.update_web_ui()
expected_response = 'Uri not found https://github.com/kytos/ui/' + \
'releases/download/1.0/latest.zip.'
self.assertEqual(response, expected_response)
@patch('kytos.core.api_server.urlretrieve')
@patch('kytos.core.api_server.urlopen')
@patch('zipfile.ZipFile')
@patch('os.path.exists')
def test_update_web_ui__zip_error(self, *args):
"""Test update_web_ui method to error case in zip file."""
(mock_exists, mock_zipfile, mock_urlopen, _) = args
zipfile = MagicMock()
zipfile.testzip.return_value = 'any'
mock_zipfile.return_value = zipfile
data = json.dumps({'tag_name': 1.0})
url_response = MagicMock()
url_response.readlines.return_value = [data]
mock_urlopen.return_value = url_response
mock_exists.return_value = False
response = self.api_server.update_web_ui()
expected_response = 'Zip file from https://github.com/kytos/ui/' + \
'releases/download/1.0/latest.zip is corrupted.'
self.assertEqual(response, expected_response)
def test_enable_napp__error_not_installed(self):
"""Test _enable_napp method error case when napp is not installed."""
self.napps_manager.is_installed.return_value = False
resp, code = self.api_server._enable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "not installed"}')
self.assertEqual(code, 400)
def test_enable_napp__error_not_enabling(self):
"""Test _enable_napp method error case when napp is not enabling."""
self.napps_manager.is_installed.return_value = True
self.napps_manager.is_enabled.side_effect = [False, False]
resp, code = self.api_server._enable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "error"}')
self.assertEqual(code, 500)
def test_enable_napp__success(self):
"""Test _enable_napp method success case."""
self.napps_manager.is_installed.return_value = True
self.napps_manager.is_enabled.side_effect = [False, True]
resp, code = self.api_server._enable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "enabled"}')
self.assertEqual(code, 200)
def test_disable_napp__error_not_installed(self):
"""Test _disable_napp method error case when napp is not installed."""
self.napps_manager.is_installed.return_value = False
resp, code = self.api_server._disable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "not installed"}')
self.assertEqual(code, 400)
def test_disable_napp__error_not_enabling(self):
"""Test _disable_napp method error case when napp is not enabling."""
self.napps_manager.is_installed.return_value = True
self.napps_manager.is_enabled.side_effect = [True, True]
resp, code = self.api_server._disable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "error"}')
self.assertEqual(code, 500)
def test_disable_napp__success(self):
"""Test _disable_napp method success case."""
self.napps_manager.is_installed.return_value = True
self.napps_manager.is_enabled.side_effect = [True, False]
resp, code = self.api_server._disable_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "disabled"}')
self.assertEqual(code, 200)
def test_install_napp__error_not_installing(self):
"""Test _install_napp method error case when napp is not installing."""
self.napps_manager.is_installed.return_value = False
self.napps_manager.install.return_value = False
resp, code = self.api_server._install_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "error"}')
self.assertEqual(code, 500)
def test_install_napp__http_error(self):
"""Test _install_napp method to http error case."""
self.napps_manager.is_installed.return_value = False
self.napps_manager.install.side_effect = HTTPError('url', 123, 'msg',
'hdrs', MagicMock())
resp, code = self.api_server._install_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "error"}')
self.assertEqual(code, 123)
def test_install_napp__success_is_installed(self):
"""Test _install_napp method success case when napp is installed."""
self.napps_manager.is_installed.return_value = True
resp, code = self.api_server._install_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "installed"}')
self.assertEqual(code, 200)
def test_install_napp__success(self):
"""Test _install_napp method success case."""
self.napps_manager.is_installed.return_value = False
self.napps_manager.install.return_value = True
resp, code = self.api_server._install_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "installed"}')
self.assertEqual(code, 200)
def test_uninstall_napp__error_not_uninstalling(self):
"""Test _uninstall_napp method error case when napp is not
uninstalling.
"""
self.napps_manager.is_installed.return_value = True
self.napps_manager.uninstall.return_value = False
resp, code = self.api_server._uninstall_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "error"}')
self.assertEqual(code, 500)
def test_uninstall_napp__success_not_installed(self):
"""Test _uninstall_napp method success case when napp is not
installed.
"""
self.napps_manager.is_installed.return_value = False
resp, code = self.api_server._uninstall_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "uninstalled"}')
self.assertEqual(code, 200)
def test_uninstall_napp__success(self):
"""Test _uninstall_napp method success case."""
self.napps_manager.is_installed.return_value = True
self.napps_manager.uninstall.return_value = True
resp, code = self.api_server._uninstall_napp('kytos', 'napp')
self.assertEqual(resp, '{"response": "uninstalled"}')
self.assertEqual(code, 200)
def test_list_enabled_napps(self):
"""Test _list_enabled_napps method."""
napp = MagicMock()
napp.username = 'kytos'
napp.name = 'name'
self.napps_manager.get_enabled_napps.return_value = [napp]
enabled_napps, code = self.api_server._list_enabled_napps()
self.assertEqual(enabled_napps, '{"napps": [["kytos", "name"]]}')
self.assertEqual(code, 200)
def test_list_installed_napps(self):
"""Test _list_installed_napps method."""
napp = MagicMock()
napp.username = 'kytos'
napp.name = 'name'
self.napps_manager.get_installed_napps.return_value = [napp]
enabled_napps, code = self.api_server._list_installed_napps()
self.assertEqual(enabled_napps, '{"napps": [["kytos", "name"]]}')
self.assertEqual(code, 200)
def test_get_napp_metadata__not_installed(self):
"""Test _get_napp_metadata method to error case when napp is not
installed."""
self.napps_manager.is_installed.return_value = False
resp, code = self.api_server._get_napp_metadata('kytos', 'napp',
'version')
self.assertEqual(resp, 'NApp is not installed.')
self.assertEqual(code, 400)
def test_get_napp_metadata__invalid_key(self):
"""Test _get_napp_metadata method to error case when key is invalid."""
self.napps_manager.is_installed.return_value = True
resp, code = self.api_server._get_napp_metadata('kytos', 'napp',
'any')
self.assertEqual(resp, 'Invalid key.')
self.assertEqual(code, 400)
def test_get_napp_metadata(self):
"""Test _get_napp_metadata method."""
data = '{"username": "kytos", \
"name": "napp", \
"version": "1.0"}'
self.napps_manager.is_installed.return_value = True
self.napps_manager.get_napp_metadata.return_value = data
resp, code = self.api_server._get_napp_metadata('kytos', 'napp',
'version')
expected_metadata = json.dumps({'version': data})
self.assertEqual(resp, expected_metadata)
self.assertEqual(code, 200)
@staticmethod
def __custom_endpoint():
"""Custom method used by APIServer."""
return "Custom Endpoint"
class RESTNApp: # pylint: disable=too-few-public-methods
"""Bare minimum for the decorator to work. Not a functional NApp."""
def __init__(self):
self.username = 'test'
self.name = 'MyNApp'
self.napp_id = 'test/MyNApp'
class TestAPIDecorator(unittest.TestCase):
"""@rest should have the same effect as ``Flask.route``."""
@classmethod
@patch('kytos.core.api_server.Blueprint')
def test_flask_call(cls, mock_blueprint):
"""@rest params should be forwarded to Flask."""
rule = 'rule'
# Use sentinels to be sure they are not changed.
options = dict(param1=sentinel.val1, param2=sentinel.val2)
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest(rule, **options)
def my_endpoint(self):
"""Do nothing."""
blueprint = Mock()
mock_blueprint.return_value = blueprint
napp = MyNApp()
cls._mock_api_server(napp)
blueprint.add_url_rule.assert_called_once_with(
'/api/test/MyNApp/' + rule, None, napp.my_endpoint, **options)
@classmethod
def test_remove_napp_endpoints(cls):
"""Test remove napp endpoints"""
class MyNApp: # pylint: disable=too-few-public-methods
"""API decorator example usage."""
def __init__(self):
self.username = 'test'
self.name = 'MyNApp'
self.napp_id = 'test/MyNApp'
napp = MyNApp()
server = cls._mock_api_server(napp)
rule = Mock()
rule.methods = ['GET', 'POST']
rule.rule.startswith.return_value = True
endpoint = 'username/napp_name'
rule.endpoint = endpoint
server.app.url_map.iter_rules.return_value = [rule]
server.app.view_functions.pop.return_value = rule
# pylint: disable=protected-access
server.app.url_map._rules.pop.return_value = rule
# pylint: enable=protected-access
server.remove_napp_endpoints(napp)
server.app.view_functions.pop.assert_called_once_with(endpoint)
# pylint: disable=protected-access
server.app.url_map._rules.pop.assert_called_once_with(0)
# pylint: enable=protected-access
server.app.blueprints.pop.assert_called_once_with(napp.napp_id)
@classmethod
@patch('kytos.core.api_server.Blueprint')
def test_rule_with_slash(cls, mock_blueprint):
"""There should be no double slashes in a rule."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
def my_endpoint(self):
"""Do nothing."""
blueprint = Mock()
mock_blueprint.return_value = blueprint
cls._assert_rule_is_added(MyNApp, blueprint)
@classmethod
@patch('kytos.core.api_server.Blueprint')
def test_rule_from_classmethod(cls, mock_blueprint):
"""Use class methods as endpoints as well."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
@classmethod
def my_endpoint(cls):
"""Do nothing."""
blueprint = Mock()
mock_blueprint.return_value = blueprint
cls._assert_rule_is_added(MyNApp, blueprint)
@classmethod
@patch('kytos.core.api_server.Blueprint')
def test_rule_from_staticmethod(cls, mock_blueprint):
"""Use static methods as endpoints as well."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
@staticmethod
def my_endpoint():
"""Do nothing."""
blueprint = Mock()
mock_blueprint.return_value = blueprint
cls._assert_rule_is_added(MyNApp, blueprint)
@classmethod
def _assert_rule_is_added(cls, napp_class, blueprint):
"""Assert Flask's add_url_rule was called with the right parameters."""
napp = napp_class()
cls._mock_api_server(napp)
blueprint.add_url_rule.assert_called_once_with(
'/api/test/MyNApp/rule', None, napp.my_endpoint)
@staticmethod
def _mock_api_server(napp):
"""Instantiate APIServer, mock ``.app`` and start ``napp`` API."""
server = APIServer('test')
server.app = Mock() # Flask app
server.app.url_map.iter_rules.return_value = []
server.register_napp_endpoints(napp)
return server
| {
"repo_name": "kytos/kytos",
"path": "tests/unit/test_core/test_api_server.py",
"copies": "1",
"size": "19870",
"license": "mit",
"hash": 840866818503415400,
"line_mean": 36.4905660377,
"line_max": 79,
"alpha_frac": 0.6061902365,
"autogenerated": false,
"ratio": 3.6926221891841666,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47988124256841663,
"avg_score": null,
"num_lines": null
} |
"""APIServer tests."""
import unittest
import warnings
# Disable not-grouped imports that conflicts with isort
from unittest.mock import Mock, sentinel # pylint: disable=C0412
from kytos.core.api_server import APIServer
from kytos.core.napps import rest
class TestAPIServer(unittest.TestCase):
"""Test the class APIServer."""
def setUp(self):
"""Instantiate a APIServer."""
self.api_server = APIServer('CustomName', False)
def test_deprecation_warning(self):
"""Deprecated method should suggest @rest decorator."""
with warnings.catch_warnings(record=True) as wrngs:
warnings.simplefilter("always") # trigger all warnings
self.api_server.register_rest_endpoint(
'rule', lambda x: x, ['POST'])
self.assertEqual(1, len(wrngs))
warning = wrngs[0]
self.assertEqual(warning.category, DeprecationWarning)
self.assertIn('@rest', str(warning.message))
@staticmethod
def __custom_endpoint():
"""Custom method used by APIServer."""
return "Custom Endpoint"
class RESTNApp: # pylint: disable=too-few-public-methods
"""Bare minimum for the decorator to work. Not a functional NApp."""
def __init__(self):
self.username = 'test'
self.name = 'MyNApp'
class TestAPIDecorator(unittest.TestCase):
"""@rest should have the same effect as ``Flask.route``."""
@classmethod
def test_flask_call(cls):
"""@rest params should be forwarded to Flask."""
rule = 'rule'
# Use sentinels to be sure they are not changed.
options = dict(param1=sentinel.val1, param2=sentinel.val2)
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest(rule, **options)
def my_endpoint(self):
"""Do nothing."""
pass
napp = MyNApp()
server = cls._mock_api_server(napp)
server.app.add_url_rule.assert_called_once_with(
'/api/test/MyNApp/' + rule, None, napp.my_endpoint, **options)
@classmethod
def test_remove_napp_endpoints(cls):
"""Test remove napp endpoints"""
class MyNApp: # pylint: disable=too-few-public-methods
"""API decorator example usage."""
def __init__(self):
self.username = 'test'
self.name = 'MyNApp'
napp = MyNApp()
server = cls._mock_api_server(napp)
rule = Mock()
rule.methods = ['GET', 'POST']
rule.rule.startswith.return_value = True
endpoint = 'username/napp_name'
rule.endpoint = endpoint
server.app.url_map.iter_rules.return_value = [rule]
server.app.view_functions.pop.return_value = rule
# pylint: disable=protected-access
server.app.url_map._rules.pop.return_value = rule
# pylint: enable=protected-access
server.remove_napp_endpoints(napp)
server.app.view_functions.pop.assert_called_once_with(endpoint)
# pylint: disable=protected-access
server.app.url_map._rules.pop.assert_called_once_with(0)
# pylint: enable=protected-access
@classmethod
def test_rule_with_slash(cls):
"""There should be no double slashes in a rule."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
def my_endpoint(self):
"""Do nothing."""
pass
cls._assert_rule_is_added(MyNApp)
@classmethod
def test_rule_from_classmethod(cls):
"""Use class methods as endpoints as well."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
@classmethod
def my_endpoint(cls):
"""Do nothing."""
pass
cls._assert_rule_is_added(MyNApp)
@classmethod
def test_rule_from_staticmethod(cls):
"""Use static methods as endpoints as well."""
class MyNApp(RESTNApp): # pylint: disable=too-few-public-methods
"""API decorator example usage."""
@rest('/rule')
@staticmethod
def my_endpoint():
"""Do nothing."""
pass
cls._assert_rule_is_added(MyNApp)
@classmethod
def _assert_rule_is_added(cls, napp_class):
"""Assert Flask's add_url_rule was called with the right parameters."""
napp = napp_class()
server = cls._mock_api_server(napp)
server.app.add_url_rule.assert_called_once_with(
'/api/test/MyNApp/rule', None, napp.my_endpoint)
@staticmethod
def _mock_api_server(napp):
"""Instantiate APIServer, mock ``.app`` and start ``napp`` API."""
server = APIServer('test')
server.app = Mock() # Flask app
server.app.url_map.iter_rules.return_value = []
server.register_napp_endpoints(napp)
return server
| {
"repo_name": "cemsbr/kytos",
"path": "tests/test_core/test_api_server.py",
"copies": "5",
"size": "5133",
"license": "mit",
"hash": 5834741432479998000,
"line_mean": 32.3311688312,
"line_max": 79,
"alpha_frac": 0.5939996104,
"autogenerated": false,
"ratio": 3.9243119266055047,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7018311537005505,
"avg_score": null,
"num_lines": null
} |
# API server URL
BASE_URL = "https://apisandbox.openbankproject.com"
API_VERSION = "v2.0.0"
API_VERSION_V210 = "v2.1.0"
API_VERSION_V220 = "v2.2.0"
# API server will redirect your browser to this URL, should be non-functional
# You will paste the redirect location here when running the script
CALLBACK_URI = 'https://apisandbox.openbankproject.com/cb'
# login user:
USERNAME = 'susan.uk.29@example.com'
PASSWORD = '2b78e8'
CONSUMER_KEY = 'mmsjy5gv3ha1achrnqfrea4u42gxi5wsowownpfb'
#Consumer Secret lez2xf3jiz1quhxxhrmdr200hpxdwjwybjmeidjd
#Consumer ID 2193
# fromAccount info:
FROM_BANK_ID = 'gh.29.uk'
FROM_ACCOUNT_ID = '8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0'
# toBankAccount and toCounterparty info(These data is from kafka side):
TO_BANK_ID = 'gh.29.uk'
TO_ACCOUNT_ID = '851273ba-90d5-43d7-bb31-ea8eba5903c7'
# TO_COUNTERPARTY_ID = 'a635f6ff-c26b-46ad-8194-2406bacceae4'
# TO_COUNTERPARTY_IBAN = 'DE12 1234 5123 4510 2207 8077 877'
# Our currency to use
OUR_CURRENCY = 'GBP'
# Our value to transfer
# values below 1000 do not require challenge request
OUR_VALUE = '1.00'
OUR_VALUE_LARGE = '1001.00'
| {
"repo_name": "OpenBankProject/Hello-OBP-DirectLogin-Python",
"path": "props/apisandbox.py",
"copies": "1",
"size": "1108",
"license": "apache-2.0",
"hash": -3097487680187681000,
"line_mean": 33.625,
"line_max": 77,
"alpha_frac": 0.7572202166,
"autogenerated": false,
"ratio": 2.4298245614035086,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.36870447780035087,
"avg_score": null,
"num_lines": null
} |
#API setup
from picraft import Vector
from picraft import World, Block
def translate_left(position, data):
if data == 0:
return position - Vector(z=1)
elif data == 1:
return position + Vector(z=1)
elif data == 2:
return position + Vector(x=1)
else:
return position - Vector(x=1)
def translate_right(position, data):
if data == 0:
return position + Vector(z=1)
elif data == 1:
return position - Vector(z=1)
elif data == 2:
return position - Vector(x=1)
else:
return position + Vector(x=1)
def rotate_clockwise(data):
if data == 0:
return 3
elif data == 1:
return 2
elif data == 2:
return 0
else:
return 1
def rotate_anticlockwise(data):
if data == 0:
return 2
elif data == 1:
return 3
elif data == 2:
return 1
else:
return 0
def face_to_dataval(face):
if face == 'x-':
return 0
elif face == 'x+':
return 1
elif face == 'z-':
return 2
elif face == 'z+':
return 3
else:
print('Error: you hit the top face')
return -1
def operation(world, position, data):
#center block
world.blocks[position] = Block(53, data)
#left block
new_position = translate_left(position, data)
new_data = rotate_clockwise(data)
world.blocks[new_position] = Block(53, new_data)
#right block
new_position = translate_right(position, data)
new_data = rotate_anticlockwise(data)
world.blocks[new_position] = Block(53, new_data)
def main():
#API setup
world = World()
while True:
#get recent sword hits
hits = world.events.poll()
for hit in hits:
#get rotation
position = hit.pos
data = face_to_dataval(hit.face)
#call the building function
if data != -1:
operation(world, position, data)
if __name__ == "__main__":
main()
| {
"repo_name": "SecretImbecile/McrRaspJam",
"path": "006_Picraft_advancedMinecraft/4_bench.py",
"copies": "2",
"size": "1719",
"license": "cc0-1.0",
"hash": 6105996816929934000,
"line_mean": 17.0947368421,
"line_max": 49,
"alpha_frac": 0.6527050611,
"autogenerated": false,
"ratio": 2.7996742671009773,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44523793282009777,
"avg_score": null,
"num_lines": null
} |
"""APIs exposed under the namespace ray.util.collective."""
import logging
import os
from typing import List
import numpy as np
import ray
from ray.util.collective import types
_NCCL_AVAILABLE = True
_GLOO_AVAILABLE = True
logger = logging.getLogger(__name__)
try:
from ray.util.collective.collective_group.\
nccl_collective_group import NCCLGroup
except ImportError:
_NCCL_AVAILABLE = False
logger.warning("NCCL seems unavailable. Please install Cupy "
"following the guide at: "
"https://docs.cupy.dev/en/stable/install.html.")
try:
from ray.util.collective.collective_group.\
gloo_collective_group import GLOOGroup
except ImportError:
_GLOO_AVAILABLE = False
logger.warning("PyGloo seems unavailable. Please install PyGloo "
"following the guide at: "
"https://github.com/ray-project/pygloo.")
def nccl_available():
return _NCCL_AVAILABLE
def gloo_available():
return _GLOO_AVAILABLE
class GroupManager(object):
"""Use this class to manage the collective groups we created so far.
Each process will have an instance of `GroupManager`. Each process
could belong to multiple collective groups. The membership information
and other metadata are stored in the global `_group_mgr` object.
"""
def __init__(self):
self._name_group_map = {}
self._group_name_map = {}
def create_collective_group(self, backend, world_size, rank, group_name):
"""The entry to create new collective groups in the manager.
Put the registration and the group information into the manager
metadata as well.
"""
backend = types.Backend(backend)
if backend == types.Backend.MPI:
raise RuntimeError("Ray does not support MPI.")
elif backend == types.Backend.GLOO:
logger.debug("Creating GLOO group: '{}'...".format(group_name))
g = GLOOGroup(
world_size,
rank,
group_name,
store_type="redis",
device_type="tcp")
self._name_group_map[group_name] = g
self._group_name_map[g] = group_name
elif backend == types.Backend.NCCL:
logger.debug("Creating NCCL group: '{}'...".format(group_name))
g = NCCLGroup(world_size, rank, group_name)
self._name_group_map[group_name] = g
self._group_name_map[g] = group_name
return self._name_group_map[group_name]
def is_group_exist(self, group_name):
return group_name in self._name_group_map
def get_group_by_name(self, group_name):
"""Get the collective group handle by its name."""
if not self.is_group_exist(group_name):
logger.warning(
"The group '{}' is not initialized.".format(group_name))
return None
return self._name_group_map[group_name]
def destroy_collective_group(self, group_name):
"""Group destructor."""
if not self.is_group_exist(group_name):
logger.warning("The group '{}' does not exist.".format(group_name))
return
# release the collective group resource
g = self._name_group_map[group_name]
# clean up the dicts
del self._group_name_map[g]
del self._name_group_map[group_name]
# Release the communicator resources
g.destroy_group()
_group_mgr = GroupManager()
def is_group_initialized(group_name):
"""Check if the group is initialized in this process by the group name."""
return _group_mgr.is_group_exist(group_name)
def init_collective_group(world_size: int,
rank: int,
backend=types.Backend.NCCL,
group_name: str = "default"):
"""Initialize a collective group inside an actor process.
Args:
world_size (int): the total number of processes in the group.
rank (int): the rank of the current process.
backend: the CCL backend to use, NCCL or GLOO.
group_name (str): the name of the collective group.
Returns:
None
"""
_check_inside_actor()
backend = types.Backend(backend)
_check_backend_availability(backend)
global _group_mgr
# TODO(Hao): implement a group auto-counter.
if not group_name:
raise ValueError("group_name '{}' needs to be a string."
.format(group_name))
if _group_mgr.is_group_exist(group_name):
raise RuntimeError("Trying to initialize a group twice.")
assert (world_size > 0)
assert (rank >= 0)
assert (rank < world_size)
_group_mgr.create_collective_group(backend, world_size, rank, group_name)
def create_collective_group(actors,
world_size: int,
ranks: List[int],
backend=types.Backend.NCCL,
group_name: str = "default"):
"""Declare a list of actors as a collective group.
Note: This function should be called in a driver process.
Args:
actors (list): a list of actors to be set in a collective group.
world_size (int): the total number of processes in the group.
ranks (List[int]): the rank of each actor.
backend: the CCL backend to use, NCCL or GLOO.
group_name (str): the name of the collective group.
Returns:
None
"""
backend = types.Backend(backend)
_check_backend_availability(backend)
name = "info_" + group_name
try:
ray.get_actor(name)
raise RuntimeError("Trying to initialize a group twice.")
except ValueError:
pass
if len(ranks) != len(actors):
raise RuntimeError(
"Each actor should correspond to one rank. Got '{}' "
"ranks but '{}' actors".format(len(ranks), len(actors)))
if set(ranks) != set(range(len(ranks))):
raise RuntimeError(
"Ranks must be a permutation from 0 to '{}'. Got '{}'.".format(
len(ranks), "".join([str(r) for r in ranks])))
if world_size <= 0:
raise RuntimeError("World size must be greater than zero. "
"Got '{}'.".format(world_size))
if not all(ranks) >= 0:
raise RuntimeError("Ranks must be non-negative.")
if not all(ranks) < world_size:
raise RuntimeError("Ranks cannot be greater than world_size.")
# avoid a circular dependency
from ray.util.collective.util import Info
# store the information into a NamedActor that can be accessed later.
name = "info_" + group_name
actors_id = [a._ray_actor_id for a in actors]
# TODO (Dacheng): how do we recycle this name actor?
info = Info.options(name=name, lifetime="detached").remote()
ray.get([info.set_info.remote(actors_id, world_size, ranks, backend)])
# TODO (we need a declarative destroy() API here.)
def destroy_collective_group(group_name: str = "default") -> None:
"""Destroy a collective group given its group name."""
_check_inside_actor()
global _group_mgr
_group_mgr.destroy_collective_group(group_name)
def get_rank(group_name: str = "default") -> int:
"""Return the rank of this process in the given group.
Args:
group_name (str): the name of the group to query
Returns:
the rank of this process in the named group,
-1 if the group does not exist or the process does
not belong to the group.
"""
_check_inside_actor()
if not is_group_initialized(group_name):
return -1
g = _group_mgr.get_group_by_name(group_name)
return g.rank
def get_collective_group_size(group_name: str = "default") -> int:
"""Return the size of the collective group with the given name.
Args:
group_name: the name of the group to query
Returns:
The world size of the collective group, -1 if the group does
not exist or the process does not belong to the group.
"""
_check_inside_actor()
if not is_group_initialized(group_name):
return -1
g = _group_mgr.get_group_by_name(group_name)
return g.world_size
def allreduce(tensor, group_name: str = "default", op=types.ReduceOp.SUM):
"""Collective allreduce the tensor across the group.
Args:
tensor: the tensor to be all-reduced on this process.
group_name (str): the collective group name to perform allreduce.
op: The reduce operation.
Returns:
None
"""
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
opts = types.AllReduceOptions
opts.reduceOp = op
g.allreduce([tensor], opts)
def allreduce_multigpu(tensor_list: list,
group_name: str = "default",
op=types.ReduceOp.SUM):
"""Collective allreduce a list of tensors across the group.
Args:
tensor_list (List[tensor]): list of tensors to be allreduced,
each on a GPU.
group_name (str): the collective group name to perform allreduce.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("Multigpu calls requires NCCL and Cupy.")
_check_tensor_list_input(tensor_list)
g = _check_and_get_group(group_name)
opts = types.AllReduceOptions
opts.reduceOp = op
g.allreduce(tensor_list, opts)
def barrier(group_name: str = "default"):
"""Barrier all processes in the collective group.
Args:
group_name (str): the name of the group to barrier.
Returns:
None
"""
g = _check_and_get_group(group_name)
g.barrier()
def reduce(tensor,
dst_rank: int = 0,
group_name: str = "default",
op=types.ReduceOp.SUM):
"""Reduce the tensor across the group to the destination rank.
Args:
tensor: the tensor to be reduced on this process.
dst_rank (int): the rank of the destination process.
group_name (str): the collective group name to perform reduce.
op: The reduce operation.
Returns:
None
"""
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
# check dst rank
_check_rank_valid(g, dst_rank)
opts = types.ReduceOptions()
opts.reduceOp = op
opts.root_rank = dst_rank
opts.root_tensor = 0
g.reduce([tensor], opts)
def reduce_multigpu(tensor_list: list,
dst_rank: int = 0,
dst_tensor: int = 0,
group_name: str = "default",
op=types.ReduceOp.SUM):
"""Reduce the tensor across the group to the destination rank
and destination tensor.
Args:
tensor_list: the list of tensors to be reduced on this process;
each tensor located on a GPU.
dst_rank (int): the rank of the destination process.
dst_tensor: the index of GPU at the destination.
group_name (str): the collective group name to perform reduce.
op: The reduce operation.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("Multigpu calls requires NCCL and Cupy.")
_check_tensor_list_input(tensor_list)
g = _check_and_get_group(group_name)
# check dst rank
_check_rank_valid(g, dst_rank)
_check_root_tensor_valid(len(tensor_list), dst_tensor)
opts = types.ReduceOptions()
opts.reduceOp = op
opts.root_rank = dst_rank
opts.root_tensor = dst_tensor
g.reduce(tensor_list, opts)
def broadcast(tensor, src_rank: int = 0, group_name: str = "default"):
"""Broadcast the tensor from a source process to all others.
Args:
tensor: the tensor to be broadcasted (src) or received (destination).
src_rank (int): the rank of the source process.
group_name (str): the collective group name to perform broadcast.
Returns:
None
"""
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
# check src rank
_check_rank_valid(g, src_rank)
opts = types.BroadcastOptions()
opts.root_rank = src_rank
opts.root_tensor = 0
g.broadcast([tensor], opts)
def broadcast_multigpu(tensor_list,
src_rank: int = 0,
src_tensor: int = 0,
group_name: str = "default"):
"""Broadcast the tensor from a source GPU to all other GPUs.
Args:
tensor_list: the tensors to broadcast (src) or receive (dst).
src_rank (int): the rank of the source process.
src_tensor (int): the index of the source GPU on the source process.
group_name (str): the collective group name to perform broadcast.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("Multigpu calls requires NCCL and Cupy.")
_check_tensor_list_input(tensor_list)
g = _check_and_get_group(group_name)
# check src rank
_check_rank_valid(g, src_rank)
_check_root_tensor_valid(len(tensor_list), src_tensor)
opts = types.BroadcastOptions()
opts.root_rank = src_rank
opts.root_tensor = src_tensor
g.broadcast(tensor_list, opts)
def allgather(tensor_list: list, tensor, group_name: str = "default"):
"""Allgather tensors from each process of the group into a list.
Args:
tensor_list (list): the results, stored as a list of tensors.
tensor: the tensor (to be gathered) in the current process
group_name (str): the name of the collective group.
Returns:
None
"""
_check_single_tensor_input(tensor)
_check_tensor_list_input(tensor_list)
g = _check_and_get_group(group_name)
if len(tensor_list) != g.world_size:
# Typically CLL lib requires len(tensor_list) >= world_size;
# Here we make it more strict: len(tensor_list) == world_size.
raise RuntimeError(
"The length of the tensor list operands to allgather "
"must be equal to world_size.")
opts = types.AllGatherOptions()
g.allgather([tensor_list], [tensor], opts)
def allgather_multigpu(output_tensor_lists: list,
input_tensor_list: list,
group_name: str = "default"):
"""Allgather tensors from each gpus of the group into lists.
Args:
output_tensor_lists (List[List[tensor]]): gathered results, with shape
must be num_gpus * world_size * shape(tensor).
input_tensor_list: (List[tensor]): a list of tensors, with shape
num_gpus * shape(tensor).
group_name (str): the name of the collective group.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("Multigpu calls requires NCCL and Cupy.")
_check_tensor_lists_input(output_tensor_lists)
_check_tensor_list_input(input_tensor_list)
g = _check_and_get_group(group_name)
opts = types.AllGatherOptions()
g.allgather(output_tensor_lists, input_tensor_list, opts)
def reducescatter(tensor,
tensor_list: list,
group_name: str = "default",
op=types.ReduceOp.SUM):
"""Reducescatter a list of tensors across the group.
Reduce the list of the tensors across each process in the group, then
scatter the reduced list of tensors -- one tensor for each process.
Args:
tensor: the resulted tensor on this process.
tensor_list (list): The list of tensors to be reduced and scattered.
group_name (str): the name of the collective group.
op: The reduce operation.
Returns:
None
"""
_check_single_tensor_input(tensor)
_check_tensor_list_input(tensor_list)
g = _check_and_get_group(group_name)
if len(tensor_list) != g.world_size:
raise RuntimeError(
"The length of the tensor list operands to reducescatter "
"must not be equal to world_size.")
opts = types.ReduceScatterOptions()
opts.reduceOp = op
g.reducescatter([tensor], [tensor_list], opts)
def reducescatter_multigpu(output_tensor_list,
input_tensor_lists,
group_name: str = "default",
op=types.ReduceOp.SUM):
"""Reducescatter a list of tensors across all GPUs.
Args:
output_tensor_list: the resulted list of tensors, with
shape: num_gpus * shape(tensor).
input_tensor_lists: the original tensors, with shape:
num_gpus * world_size * shape(tensor).
group_name (str): the name of the collective group.
op: The reduce operation.
Returns:
None.
"""
if not types.cupy_available():
raise RuntimeError("Multigpu calls requires NCCL and Cupy.")
_check_tensor_lists_input(input_tensor_lists)
_check_tensor_list_input(output_tensor_list)
g = _check_and_get_group(group_name)
opts = types.ReduceScatterOptions()
opts.reduceOp = op
g.reducescatter(output_tensor_list, input_tensor_lists, opts)
def send(tensor, dst_rank: int, group_name: str = "default"):
"""Send a tensor to a remote process synchronously.
Args:
tensor: the tensor to send.
dst_rank (int): the rank of the destination process.
group_name (str): the name of the collective group.
Returns:
None
"""
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
_check_rank_valid(g, dst_rank)
if dst_rank == g.rank:
raise RuntimeError(
"The destination rank '{}' is self.".format(dst_rank))
opts = types.SendOptions()
opts.dst_rank = dst_rank
g.send([tensor], opts)
def send_multigpu(tensor,
dst_rank: int,
dst_gpu_index: int,
group_name: str = "default"):
"""Send a tensor to a remote GPU synchronously.
The function asssume each process owns >1 GPUs, and the sender
process and receiver process has equal nubmer of GPUs.
Args:
tensor: the tensor to send, located on a GPU.
dst_rank (int): the rank of the destination process.
dst_gpu_index (int): the destination gpu index.
group_name (str): the name of the collective group.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("send_multigpu call requires NCCL.")
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
_check_rank_valid(g, dst_rank)
if dst_rank == g.rank:
raise RuntimeError("The dst_rank '{}' is self. Considering "
"doing GPU to GPU memcpy instead?".format(dst_rank))
opts = types.SendOptions()
opts.dst_rank = dst_rank
opts.dst_gpu_index = dst_gpu_index
g.send([tensor], opts)
def recv(tensor, src_rank: int, group_name: str = "default"):
"""Receive a tensor from a remote process synchronously.
Args:
tensor: the received tensor.
src_rank (int): the rank of the source process.
group_name (str): the name of the collective group.
Returns:
None
"""
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
_check_rank_valid(g, src_rank)
if src_rank == g.rank:
raise RuntimeError(
"The destination rank '{}' is self.".format(src_rank))
opts = types.RecvOptions()
opts.src_rank = src_rank
g.recv([tensor], opts)
def recv_multigpu(tensor,
src_rank: int,
src_gpu_index: int,
group_name: str = "default"):
"""Receive a tensor from a remote GPU synchronously.
The function asssume each process owns >1 GPUs, and the sender
process and receiver process has equal nubmer of GPUs.
Args:
tensor: the received tensor, located on a GPU.
src_rank (int): the rank of the source process.
src_gpu_index (int): the index of the source gpu on the src process.
group_name (str): the name of the collective group.
Returns:
None
"""
if not types.cupy_available():
raise RuntimeError("recv_multigpu call requires NCCL.")
_check_single_tensor_input(tensor)
g = _check_and_get_group(group_name)
_check_rank_valid(g, src_rank)
if src_rank == g.rank:
raise RuntimeError("The dst_rank '{}' is self. Considering "
"doing GPU to GPU memcpy instead?".format(src_rank))
opts = types.RecvOptions()
opts.src_rank = src_rank
opts.src_gpu_index = src_gpu_index
g.recv([tensor], opts)
def _check_and_get_group(group_name):
"""Check the existence and return the group handle."""
_check_inside_actor()
global _group_mgr
if not is_group_initialized(group_name):
# try loading from remote info store
try:
# if the information is stored in an Info object,
# get and create the group.
name = "info_" + group_name
mgr = ray.get_actor(name=name)
ids, world_size, rank, backend = ray.get(mgr.get_info.remote())
worker = ray.worker.global_worker
id_ = worker.core_worker.get_actor_id()
r = rank[ids.index(id_)]
_group_mgr.create_collective_group(backend, world_size, r,
group_name)
except ValueError as exc:
# check if this group is initialized using options()
if "collective_group_name" in os.environ and \
os.environ["collective_group_name"] == group_name:
rank = int(os.environ["collective_rank"])
world_size = int(os.environ["collective_world_size"])
backend = os.environ["collective_backend"]
_group_mgr.create_collective_group(backend, world_size, rank,
group_name)
else:
raise RuntimeError(
"The collective group '{}' is not "
"initialized in the process.".format(group_name)) from exc
g = _group_mgr.get_group_by_name(group_name)
return g
def _check_single_tensor_input(tensor):
"""Check if the tensor is with a supported type."""
if isinstance(tensor, np.ndarray):
return
if types.cupy_available():
if isinstance(tensor, types.cp.ndarray):
return
if types.torch_available():
if isinstance(tensor, types.th.Tensor):
return
raise RuntimeError("Unrecognized tensor type '{}'. Supported types are: "
"np.ndarray, torch.Tensor, cupy.ndarray.".format(
type(tensor)))
def _check_backend_availability(backend: types.Backend):
"""Check whether the backend is available."""
if backend == types.Backend.GLOO:
if not gloo_available():
raise RuntimeError("GLOO is not available.")
elif backend == types.Backend.NCCL:
if not nccl_available():
raise RuntimeError("NCCL is not available.")
def _check_inside_actor():
"""Check if currently it is inside a Ray actor/task."""
worker = ray.worker.global_worker
if worker.mode == ray.WORKER_MODE:
return
else:
raise RuntimeError("The collective APIs shall be only used inside "
"a Ray actor or task.")
def _check_rank_valid(g, rank: int):
"""Check the rank: 0 <= rank < world_size."""
if rank < 0:
raise ValueError("rank '{}' is negative.".format(rank))
if rank >= g.world_size:
raise ValueError("rank '{}' must be less than world size "
"'{}'".format(rank, g.world_size))
def _check_tensor_list_input(tensor_list):
"""Check if the input is a list of supported tensor types."""
if not isinstance(tensor_list, list):
raise RuntimeError("The input must be a list of tensors. "
"Got '{}'.".format(type(tensor_list)))
if not tensor_list:
raise RuntimeError("Got an empty list of tensors.")
for t in tensor_list:
_check_single_tensor_input(t)
def _check_tensor_lists_input(tensor_lists):
"""Check if the input is a list of lists of supported tensor types."""
if not isinstance(tensor_lists, list):
raise RuntimeError("The input must be a list of lists of tensors. "
"Got '{}'.".format(type(tensor_lists)))
if not tensor_lists:
raise RuntimeError(f"Did not receive tensors. Got: {tensor_lists}")
for t in tensor_lists:
_check_tensor_list_input(t)
def _check_root_tensor_valid(length, root_tensor):
"""Check the root_tensor device is 0 <= root_tensor < length"""
if root_tensor < 0:
raise ValueError("root_tensor '{}' is negative.".format(root_tensor))
if root_tensor >= length:
raise ValueError(
"root_tensor '{}' is greater than the number of GPUs: "
"'{}'".format(root_tensor, length))
| {
"repo_name": "ray-project/ray",
"path": "python/ray/util/collective/collective.py",
"copies": "1",
"size": "25149",
"license": "apache-2.0",
"hash": -8688809361045979000,
"line_mean": 33.3538251366,
"line_max": 79,
"alpha_frac": 0.6104505508,
"autogenerated": false,
"ratio": 3.911494789236273,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 732
} |
"""APIs for coudsync app"""
import re
from collections import namedtuple
from datetime import datetime
from urllib.parse import quote
import pytz
import boto3
from boto3.s3.transfer import TransferConfig
from botocore.exceptions import ClientError
from django.conf import settings
from django.contrib.auth.models import User
from django.db import transaction
from cloudsync.utils import VideoTranscoder
from ui.constants import VideoStatus
from ui.encodings import EncodingNames
from ui.models import (
TRANSCODE_PREFIX,
VideoFile,
VideoThumbnail,
Collection,
Video,
VideoSubtitle,
delete_s3_objects,
)
from ui.utils import get_et_preset, get_bucket, get_et_job
from odl_video import logging
log = logging.getLogger(__name__)
THUMBNAIL_PATTERN = "thumbnails/{}_thumbnail_{{count}}"
RETRANSCODE_FOLDER = "retranscode/"
ParsedVideoAttributes = namedtuple(
"ParsedVideoAttributes",
["prefix", "session", "record_date", "record_date_str", "name"],
)
def process_transcode_results(video, job):
"""
Create VideoFile and VideoThumbnail objects for a Video based on AWS ET job output
Args:
video(Video): Video object to which files and thumbnails belong
job(JSON): JSON representation of AWS ET job output
"""
if video.status == VideoStatus.RETRANSCODING:
# Overwrite old playlists/files with new transcoding output
move_s3_objects(
settings.VIDEO_S3_TRANSCODE_BUCKET,
f"{RETRANSCODE_FOLDER}{TRANSCODE_PREFIX}/{video.hexkey}",
f"{TRANSCODE_PREFIX}/{video.hexkey}",
)
for playlist in job["Playlists"]:
VideoFile.objects.update_or_create(
# This assumes HLS encoding
s3_object_key="{}.m3u8".format(
playlist["Name"].replace(RETRANSCODE_FOLDER, "")
),
defaults={
"video": video,
"bucket_name": settings.VIDEO_S3_TRANSCODE_BUCKET,
"encoding": EncodingNames.HLS,
"preset_id": ",".join(
[output["PresetId"] for output in job["Outputs"]]
),
},
)
for output in job["Outputs"]:
if "ThumbnailPattern" not in output:
continue
thumbnail_pattern = output["ThumbnailPattern"].replace("{count}", "")
preset = get_et_preset(output["PresetId"])
bucket = get_bucket(settings.VIDEO_S3_THUMBNAIL_BUCKET)
for thumb in bucket.objects.filter(Prefix=thumbnail_pattern):
VideoThumbnail.objects.update_or_create(
s3_object_key=thumb.key.replace(RETRANSCODE_FOLDER, ""),
defaults={
"video": video,
"bucket_name": settings.VIDEO_S3_THUMBNAIL_BUCKET,
"preset_id": output["PresetId"],
"max_height": int(preset["Thumbnails"]["MaxHeight"]),
"max_width": int(preset["Thumbnails"]["MaxWidth"]),
},
)
def get_error_type_from_et_error(et_error):
"""
Parses an Elastic transcoder error string and matches the error to an error in VideoStatus
Args:
et_error (str): a string representing the description of the Elastic Transcoder Error
Returns:
ui.constants.VideoStatus: a string representing the video status
"""
if not et_error:
log.error("Elastic transcoder did not return an error string")
return VideoStatus.TRANSCODE_FAILED_INTERNAL
error_code = et_error.split(" ")[0]
try:
error_code = int(error_code)
except ValueError:
log.error("Elastic transcoder did not return an expected error string")
return VideoStatus.TRANSCODE_FAILED_INTERNAL
if 4000 <= error_code < 5000:
return VideoStatus.TRANSCODE_FAILED_VIDEO
return VideoStatus.TRANSCODE_FAILED_INTERNAL
def refresh_status(video, encode_job=None):
"""
Check the encode job status & if not complete, update the status via a query to AWS.
Args:
video(ui.models.Video): Video object to refresh status of.
encode_job(dj_elastictranscoder.models.EncodeJob): EncodeJob associated with Video
"""
if video.status in (VideoStatus.TRANSCODING, VideoStatus.RETRANSCODING):
if not encode_job:
encode_job = video.encode_jobs.latest("created_at")
et_job = get_et_job(encode_job.id)
if et_job["Status"] == VideoStatus.COMPLETE:
process_transcode_results(video, et_job)
video.update_status(VideoStatus.COMPLETE)
elif et_job["Status"] == VideoStatus.ERROR:
if video.status == VideoStatus.RETRANSCODING:
video.update_status(VideoStatus.RETRANSCODE_FAILED)
else:
video.update_status(
get_error_type_from_et_error(
et_job.get("Output", {}).get("StatusDetail")
)
)
log.error("Transcoding failed", video_id=video.id)
encode_job.message = et_job
encode_job.save()
def transcode_video(video, video_file):
"""
Start a transcode job for a video
Args:
video(ui.models.Video): the video to transcode
video_file(ui.models.Videofile): the s3 file to use for transcoding
"""
video_input = {
"Key": video_file.s3_object_key,
}
if video.status == VideoStatus.RETRANSCODE_SCHEDULED:
# Retranscode to a temporary folder and delete any stray S3 objects from there
prefix = RETRANSCODE_FOLDER
# pylint:disable=no-value-for-parameter
delete_s3_objects(
settings.VIDEO_S3_TRANSCODE_BUCKET,
f"{prefix}{TRANSCODE_PREFIX}/{video.hexkey}",
as_filter=True,
)
else:
prefix = ""
# Generate an output video file for each encoding (assumed to be HLS)
outputs = [
{
"Key": f"{prefix}{video.transcode_key(preset)}",
"PresetId": preset,
"SegmentDuration": "10.0",
}
for preset in settings.ET_PRESET_IDS
]
playlists = [
{
"Format": "HLSv3",
"Name": f"{prefix}{video.transcode_key('_index')}",
"OutputKeys": [output["Key"] for output in outputs],
}
]
# Generate thumbnails for the 1st encoding (no point in doing so for each).
if video.status != VideoStatus.RETRANSCODE_SCHEDULED:
outputs[0][
"ThumbnailPattern"
] = f"{prefix}{THUMBNAIL_PATTERN.format(video_file.s3_basename)}"
transcoder = VideoTranscoder(
settings.ET_PIPELINE_ID,
settings.AWS_REGION,
settings.AWS_ACCESS_KEY_ID,
settings.AWS_SECRET_ACCESS_KEY,
)
user_meta = {
"pipeline": "odl-video-service-{}".format(settings.ENVIRONMENT).lower()
}
try:
transcoder.encode(
video_input, outputs, Playlists=playlists, UserMetadata=user_meta
)
except ClientError as exc:
log.error("Transcode job creation failed", video_id=video.id)
if video.status == VideoStatus.RETRANSCODE_SCHEDULED:
video.status = VideoStatus.RETRANSCODE_FAILED
else:
video.update_status(VideoStatus.TRANSCODE_FAILED_INTERNAL)
video.save()
if hasattr(exc, "response"):
transcoder.message = exc.response
raise
finally:
transcoder.create_job_for_object(video)
if video.status == VideoStatus.RETRANSCODE_SCHEDULED:
video.update_status(VideoStatus.RETRANSCODING)
elif video.status not in (
VideoStatus.TRANSCODE_FAILED_INTERNAL,
VideoStatus.TRANSCODE_FAILED_VIDEO,
VideoStatus.RETRANSCODE_FAILED,
):
video.update_status(VideoStatus.TRANSCODING)
def create_lecture_collection_slug(video_attributes):
"""
Create a name for a collection based on some attributes of an uploaded video filename
Args:
video_attributes (ParsedVideoAttributes): Named tuple of lecture video info
"""
return (
video_attributes.prefix
if not video_attributes.session
else "{}-{}".format(video_attributes.prefix, video_attributes.session)
)
def create_lecture_video_title(video_attributes):
"""
Create a title for a video based on some attributes of an uploaded video filename
Args:
video_attributes (ParsedVideoAttributes): Named tuple of lecture video info
"""
video_title_date = (
video_attributes.record_date_str
if not video_attributes.record_date
else video_attributes.record_date.strftime("%B %d, %Y")
)
return (
"Lecture - {}".format(video_title_date)
if video_title_date
else video_attributes.name
)
def process_watch_file(s3_filename):
"""
Move the file from the watch bucket to the upload bucket, create model objects, and transcode.
The given file is assumed to be a lecture capture video.
Args:
s3_filename (str): S3 object key (i.e.: a filename)
"""
watch_bucket = get_bucket(settings.VIDEO_S3_WATCH_BUCKET)
video_attributes = parse_lecture_video_filename(s3_filename)
collection_slug = create_lecture_collection_slug(video_attributes)
collection, _ = Collection.objects.get_or_create(
slug=collection_slug,
owner=User.objects.get(username=settings.LECTURE_CAPTURE_USER),
defaults={"title": collection_slug},
)
with transaction.atomic():
video = Video.objects.create(
source_url="https://{}/{}/{}".format(
settings.AWS_S3_DOMAIN,
settings.VIDEO_S3_WATCH_BUCKET,
quote(s3_filename),
),
collection=collection,
title=create_lecture_video_title(video_attributes),
multiangle=True, # Assume all videos in watch bucket are multi-angle
)
video_file = VideoFile.objects.create(
s3_object_key=video.get_s3_key(),
video_id=video.id,
bucket_name=settings.VIDEO_S3_BUCKET,
)
# Copy the file to the upload bucket using a new s3 key
s3_client = boto3.client("s3")
copy_source = {"Bucket": watch_bucket.name, "Key": s3_filename}
try:
s3_client.copy(copy_source, settings.VIDEO_S3_BUCKET, video_file.s3_object_key)
except:
try:
video.delete()
except:
log.error(
"Failed to delete video after failed S3 file copy",
video_hexkey=video.hexkey,
)
raise
raise
# Delete the original file from the watch bucket
try:
s3_client.delete_object(Bucket=settings.VIDEO_S3_WATCH_BUCKET, Key=s3_filename)
except ClientError:
log.error("Failed to delete from watch bucket", s3_object_key=s3_filename)
# Start a transcode job for the video
transcode_video(video, video_file)
def parse_lecture_video_filename(filename):
"""
Parses the filename for required course information
Args:
filename(str): The name of the video file, in format
'MIT-<course#>-<year>-<semester>-lec-mit-0000-<recording_date>-<time>-<session>.mp4'
Returns:
ParsedVideoAttributes: A named tuple of information extracted from the video file name
"""
rx = (
r"(.+)-lec-mit-0000-" # prefix to be used as the start of the collection name
r"(\w+)" # Recording date (required)
r"-(\d+)" # Recording time (required)
r"(-([L\d\-]+))?" # Session or room number (optional)
r".*\.\w"
) # Rest of filename including extension (required)
matches = re.search(rx, filename)
if not matches or len(matches.groups()) != 5:
log.exception(
"No matches found for filename %s with regex %s",
positional_args=(filename, rx),
filename=filename,
)
prefix = settings.UNSORTED_COLLECTION
session = ""
recording_date_str = ""
record_date = None
else:
prefix, recording_date_str, _, _, session = matches.groups()
try:
record_date = datetime.strptime(recording_date_str, "%Y%b%d")
except ValueError:
record_date = None
return ParsedVideoAttributes(
prefix=prefix,
session=session,
record_date=record_date,
record_date_str=recording_date_str,
name=filename,
)
def upload_subtitle_to_s3(caption_data, file_data):
"""
Uploads a subtitle file to S3
Args:
caption_data(dict): Subtitle upload data
file_data(InMemoryUploadedFile): File being uploaded
Returns:
VideoSubtitle or None: New or updated VideoSubtitle (or None)
"""
video_key = caption_data.get("video")
filename = caption_data.get("filename")
language = caption_data.get("language", "en")
if not video_key:
return None
try:
video = Video.objects.get(key=video_key)
except Video.DoesNotExist:
log.error(
"Attempted to upload subtitle to Video that does not exist",
video_key=video_key,
)
raise
s3 = boto3.resource("s3")
bucket_name = settings.VIDEO_S3_SUBTITLE_BUCKET
bucket = s3.Bucket(bucket_name)
config = TransferConfig(**settings.AWS_S3_UPLOAD_TRANSFER_CONFIG)
s3_key = video.subtitle_key(datetime.now(tz=pytz.UTC), language)
try:
bucket.upload_fileobj(
Fileobj=file_data,
Key=s3_key,
ExtraArgs={"ContentType": "mime/vtt"},
Config=config,
)
except Exception:
log.error("An error occurred uploading caption file", video_key=video_key)
raise
vt, created = VideoSubtitle.objects.get_or_create(
video=video,
language=language,
bucket_name=bucket_name,
defaults={"s3_object_key": s3_key},
)
if not created:
try:
vt.delete_from_s3()
except ClientError:
log.exception(
"Could not delete old subtitle from S3", s3_object_key=vt.s3_object_key
)
vt.s3_object_key = s3
vt.filename = filename
vt.s3_object_key = s3_key
vt.save()
return vt
def move_s3_objects(bucket_name, from_prefix, to_prefix):
"""
Copies files from one prefix (subfolder) to another, then deletes the originals
Args:
bucket_name (str): The bucket name
from_prefix(str): The subfolder to copy from
to_prefix(str): The subfolder to copy to
"""
bucket = get_bucket(bucket_name)
for obj in bucket.objects.filter(Prefix=from_prefix):
copy_src = {"Bucket": bucket_name, "Key": obj.key}
bucket.copy(copy_src, Key=obj.key.replace(from_prefix, to_prefix))
delete_s3_objects.delay(bucket_name, from_prefix, as_filter=True)
| {
"repo_name": "mitodl/odl-video-service",
"path": "cloudsync/api.py",
"copies": "1",
"size": "14957",
"license": "bsd-3-clause",
"hash": -7890338256258983000,
"line_mean": 32.9931818182,
"line_max": 98,
"alpha_frac": 0.6175703684,
"autogenerated": false,
"ratio": 3.9082832505879277,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5025853618987928,
"avg_score": null,
"num_lines": null
} |
"""APIs for creating user-defined element-wise, reduction and analytic
functions.
"""
from __future__ import absolute_import
import collections
import functools
import itertools
from typing import Tuple
import numpy as np
import pandas as pd
from pandas.core.groupby import SeriesGroupBy
import ibis.client
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
import ibis.udf.vectorized
from ibis.util import coerce_to_dataframe
from .aggcontext import Summarize, Transform
from .core import date_types, time_types, timedelta_types, timestamp_types
from .dispatch import execute_node, pre_execute
@functools.singledispatch
def rule_to_python_type(datatype):
"""Convert an ibis :class:`~ibis.expr.datatypes.DataType` into a pandas
backend friendly ``multipledispatch`` signature.
Parameters
----------
rule : DataType
The :class:`~ibis.expr.datatypes.DataType` subclass to map to a pandas
friendly type.
Returns
-------
Union[Type[U], Tuple[Type[T], ...]]
A pandas-backend-friendly signature
"""
raise NotImplementedError(
"Don't know how to convert type {} into a native Python type".format(
type(datatype)
)
)
def create_gens_from_args_groupby(args: Tuple[SeriesGroupBy]):
""" Create generators for each args for groupby udaf.
Returns a generator that outputs each group.
Parameters
----------
args : Tuple[SeriesGroupBy...]
Returns
-------
Tuple[Generator]
"""
iters = ((data for _, data in arg) for arg in args)
return iters
@rule_to_python_type.register(dt.Array)
def array_rule(rule):
return (list,)
@rule_to_python_type.register(dt.Map)
def map_rule(rule):
return (dict,)
@rule_to_python_type.register(dt.Struct)
def struct_rule(rule):
return (collections.OrderedDict,)
@rule_to_python_type.register(dt.String)
def string_rule(rule):
return (str,)
@rule_to_python_type.register(dt.Integer)
def int_rule(rule):
return int, np.integer
@rule_to_python_type.register(dt.Floating)
def float_rule(rule):
return float, np.floating
@rule_to_python_type.register(dt.Boolean)
def bool_rule(rule):
return bool, np.bool_
@rule_to_python_type.register(dt.Interval)
def interval_rule(rule):
return timedelta_types
@rule_to_python_type.register(dt.Date)
def date_rule(rule):
return date_types
@rule_to_python_type.register(dt.Timestamp)
def timestamp_rule(rule):
return timestamp_types
@rule_to_python_type.register(dt.Time)
def time_rule(rule):
return time_types
def nullable(datatype):
"""Return the signature of a scalar value that is allowed to be NULL (in
SQL parlance).
Parameters
----------
datatype : ibis.expr.datatypes.DataType
Returns
-------
Tuple[Type]
"""
return (type(None),) if datatype.nullable else ()
class udf:
@staticmethod
def elementwise(input_type, output_type):
"""Alias for ibis.udf.vectorized.elementwise."""
return ibis.udf.vectorized.elementwise(input_type, output_type)
@staticmethod
def reduction(input_type, output_type):
"""Alias for ibis.udf.vectorized.reduction."""
return ibis.udf.vectorized.reduction(input_type, output_type)
@staticmethod
def analytic(input_type, output_type):
"""Alias for ibis.udf.vectorized.analytic."""
return ibis.udf.vectorized.analytic(input_type, output_type)
@pre_execute.register(ops.ElementWiseVectorizedUDF)
@pre_execute.register(ops.ElementWiseVectorizedUDF, ibis.client.Client)
def pre_execute_elementwise_udf(op, *clients, scope=None, **kwargs):
"""Register execution rules for elementwise UDFs.
"""
input_type = op.input_type
# definitions
# Define an execution rule for elementwise operations on a
# grouped Series
nargs = len(input_type)
@execute_node.register(
ops.ElementWiseVectorizedUDF, *(itertools.repeat(SeriesGroupBy, nargs))
)
def execute_udf_node_groupby(op, *args, **kwargs):
func = op.func
groupers = [
grouper
for grouper in (getattr(arg, 'grouper', None) for arg in args)
if grouper is not None
]
# all grouping keys must be identical
assert all(groupers[0] == grouper for grouper in groupers[1:])
# we're performing a scalar operation on grouped column, so
# perform the operation directly on the underlying Series
# and regroup after it's finished
args = [getattr(arg, 'obj', arg) for arg in args]
groupings = groupers[0].groupings
return func(*args).groupby(groupings)
# Define an execution rule for a simple elementwise Series
# function
@execute_node.register(
ops.ElementWiseVectorizedUDF, *(itertools.repeat(pd.Series, nargs))
)
@execute_node.register(
ops.ElementWiseVectorizedUDF, *(itertools.repeat(object, nargs))
)
def execute_udf_node(op, *args, **kwargs):
# We have rewritten op.func to be a closure enclosing
# the kwargs, and therefore, we do not need to pass
# kwargs here. This is true for all udf execution in this
# file.
# See ibis.udf.vectorized.UserDefinedFunction
return op.func(*args)
return scope
@pre_execute.register(ops.AnalyticVectorizedUDF)
@pre_execute.register(ops.AnalyticVectorizedUDF, ibis.client.Client)
@pre_execute.register(ops.ReductionVectorizedUDF)
@pre_execute.register(ops.ReductionVectorizedUDF, ibis.client.Client)
def pre_execute_analytic_and_reduction_udf(op, *clients, scope=None, **kwargs):
input_type = op.input_type
nargs = len(input_type)
# An execution rule to handle analytic and reduction UDFs over
# 1) an ungrouped window,
# 2) an ungrouped Aggregate node, or
# 3) an ungrouped custom aggregation context
@execute_node.register(type(op), *(itertools.repeat(pd.Series, nargs)))
def execute_udaf_node_no_groupby(op, *args, aggcontext, **kwargs):
return aggcontext.agg(args[0], op.func, *args[1:])
# An execution rule to handle analytic and reduction UDFs over
# 1) a grouped window,
# 2) a grouped Aggregate node, or
# 3) a grouped custom aggregation context
@execute_node.register(type(op), *(itertools.repeat(SeriesGroupBy, nargs)))
def execute_udaf_node_groupby(op, *args, aggcontext, **kwargs):
func = op.func
if isinstance(aggcontext, Transform):
# We are either:
# 1) Aggregating over an unbounded (and GROUPED) window, which
# uses a Transform aggregation context
# 2) Aggregating using an Aggregate node (with GROUPING), which
# uses a Summarize aggregation context
# We need to do some pre-processing to func and args so that
# Transform or Summarize can pull data out of the SeriesGroupBys
# in args.
# Construct a generator that yields the next group of data
# for every argument excluding the first (pandas performs
# the iteration for the first argument) for each argument
# that is a SeriesGroupBy.
iters = create_gens_from_args_groupby(args[1:])
# TODO: Unify calling convension here to be more like
# window
def aggregator(first, *rest):
# map(next, *rest) gets the inputs for the next group
# TODO: might be inefficient to do this on every call
result = func(first, *map(next, rest))
# Here we don't user execution.util.coerce_to_output
# because this is the inner loop and we do not want
# to wrap a scalar value with a series.
if isinstance(op._output_type, dt.Struct):
return coerce_to_dataframe(result, op._output_type.names)
else:
return result
return aggcontext.agg(args[0], aggregator, *iters)
elif isinstance(aggcontext, Summarize):
iters = create_gens_from_args_groupby(args[1:])
# TODO: Unify calling convension here to be more like
# window
def aggregator(first, *rest):
# map(next, *rest) gets the inputs for the next group
# TODO: might be inefficient to do this on every call
return func(first, *map(next, rest))
return aggcontext.agg(args[0], aggregator, *iters)
else:
# We are either:
# 1) Aggregating over a bounded window, which uses a Window
# aggregation context
# 2) Aggregating over a custom aggregation context
# No pre-processing to be done for either case.
return aggcontext.agg(args[0], func, *args[1:])
return scope
| {
"repo_name": "cloudera/ibis",
"path": "ibis/backends/pandas/udf.py",
"copies": "1",
"size": "8896",
"license": "apache-2.0",
"hash": -2542837898634921000,
"line_mean": 30.4346289753,
"line_max": 79,
"alpha_frac": 0.6545638489,
"autogenerated": false,
"ratio": 3.89492119089317,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 283
} |
"""APIs for creating user-defined element-wise, reduction and analytic
functions.
"""
from __future__ import absolute_import
import collections
import functools
import itertools
import operator
from inspect import Parameter, signature
import numpy as np
import pandas as pd
import toolz
from pandas.core.groupby import SeriesGroupBy
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
import ibis.expr.signature as sig
from ibis.pandas.core import (
date_types,
time_types,
timedelta_types,
timestamp_types,
)
from ibis.pandas.dispatch import execute_node
@functools.singledispatch
def rule_to_python_type(datatype):
"""Convert an ibis :class:`~ibis.expr.datatypes.DataType` into a pandas
backend friendly ``multipledispatch`` signature.
Parameters
----------
rule : DataType
The :class:`~ibis.expr.datatypes.DataType` subclass to map to a pandas
friendly type.
Returns
-------
Union[Type[U], Tuple[Type[T], ...]]
A pandas-backend-friendly signature
"""
raise NotImplementedError(
"Don't know how to convert type {} into a native Python type".format(
type(datatype)
)
)
def arguments_from_signature(signature, *args, **kwargs):
"""Validate signature against `args` and `kwargs` and return the kwargs
asked for in the signature
Parameters
----------
args : Tuple[object...]
kwargs : Dict[str, object]
Returns
-------
Tuple[Tuple, Dict[str, Any]]
Examples
--------
>>> from inspect import signature
>>> def foo(a, b=1):
... return a + b
>>> foo_sig = signature(foo)
>>> args, kwargs = arguments_from_signature(foo_sig, 1, b=2)
>>> args
(1,)
>>> kwargs
{'b': 2}
>>> def bar(a):
... return a + 1
>>> bar_sig = signature(bar)
>>> args, kwargs = arguments_from_signature(bar_sig, 1, b=2)
>>> args
(1,)
>>> kwargs
{}
"""
bound = signature.bind_partial(*args)
meta_kwargs = toolz.merge({'kwargs': kwargs}, kwargs)
remaining_parameters = signature.parameters.keys() - bound.arguments.keys()
new_kwargs = {
k: meta_kwargs[k]
for k in remaining_parameters
if k in signature.parameters
if signature.parameters[k].kind
in {
Parameter.KEYWORD_ONLY,
Parameter.POSITIONAL_OR_KEYWORD,
Parameter.VAR_KEYWORD,
}
}
return args, new_kwargs
@rule_to_python_type.register(dt.Array)
def array_rule(rule):
return (list,)
@rule_to_python_type.register(dt.Map)
def map_rule(rule):
return (dict,)
@rule_to_python_type.register(dt.Struct)
def struct_rule(rule):
return (collections.OrderedDict,)
@rule_to_python_type.register(dt.String)
def string_rule(rule):
return (str,)
@rule_to_python_type.register(dt.Integer)
def int_rule(rule):
return int, np.integer
@rule_to_python_type.register(dt.Floating)
def float_rule(rule):
return float, np.floating
@rule_to_python_type.register(dt.Boolean)
def bool_rule(rule):
return bool, np.bool_
@rule_to_python_type.register(dt.Interval)
def interval_rule(rule):
return timedelta_types
@rule_to_python_type.register(dt.Date)
def date_rule(rule):
return date_types
@rule_to_python_type.register(dt.Timestamp)
def timestamp_rule(rule):
return timestamp_types
@rule_to_python_type.register(dt.Time)
def time_rule(rule):
return time_types
def nullable(datatype):
"""Return the signature of a scalar value that is allowed to be NULL (in
SQL parlance).
Parameters
----------
datatype : ibis.expr.datatypes.DataType
Returns
-------
Tuple[Type]
"""
return (type(None),) if datatype.nullable else ()
def udf_signature(input_type, pin, klass):
"""Compute the appropriate signature for a
:class:`~ibis.expr.operations.Node` from a list of input types
`input_type`.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of :class:`~ibis.expr.datatypes.DataType` instances representing
the signature of a UDF/UDAF.
pin : Optional[int]
If this is not None, pin the `pin`-th argument type to `klass`
klass : Union[Type[pd.Series], Type[SeriesGroupBy]]
The pandas object that every argument type should contain
Returns
-------
Tuple[Type]
A tuple of types appropriate for use in a multiple dispatch signature.
Examples
--------
>>> from pprint import pprint
>>> import pandas as pd
>>> from pandas.core.groupby import SeriesGroupBy
>>> import ibis.expr.datatypes as dt
>>> input_type = [dt.string, dt.double]
>>> sig = udf_signature(input_type, pin=None, klass=pd.Series)
>>> pprint(sig) # doctest: +ELLIPSIS
((<class '...Series'>, <... '...str...'>, <... 'NoneType'>),
(<class '...Series'>,
<... 'float'>,
<... 'numpy.floating'>,
<... 'NoneType'>))
>>> not_nullable_types = [
... dt.String(nullable=False), dt.Double(nullable=False)]
>>> sig = udf_signature(not_nullable_types, pin=None, klass=pd.Series)
>>> pprint(sig) # doctest: +ELLIPSIS
((<class '...Series'>, <... '...str...'>),
(<class '...Series'>,
<... 'float'>,
<... 'numpy.floating'>))
>>> sig0 = udf_signature(input_type, pin=0, klass=SeriesGroupBy)
>>> sig1 = udf_signature(input_type, pin=1, klass=SeriesGroupBy)
>>> pprint(sig0) # doctest: +ELLIPSIS
(<class '...SeriesGroupBy'>,
(<class '...SeriesGroupBy'>,
<... 'float'>,
<... 'numpy.floating'>,
<... 'NoneType'>))
>>> pprint(sig1) # doctest: +ELLIPSIS
((<class '...SeriesGroupBy'>,
<... '...str...'>,
<... 'NoneType'>),
<class '...SeriesGroupBy'>)
"""
nargs = len(input_type)
if not nargs:
return ()
if nargs == 1:
r, = input_type
result = (klass,) + rule_to_python_type(r) + nullable(r)
return (result,)
return tuple(
klass
if pin is not None and pin == i
else ((klass,) + rule_to_python_type(r) + nullable(r))
for i, r in enumerate(input_type)
)
def parameter_count(funcsig):
"""Get the number of positional-or-keyword or position-only parameters in a
function signature.
Parameters
----------
funcsig : inspect.Signature
A UDF signature
Returns
-------
int
The number of parameters
"""
return sum(
param.kind in {param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY}
for param in funcsig.parameters.values()
if param.default is Parameter.empty
)
def valid_function_signature(input_type, func):
"""Check that the declared number of inputs (the length of `input_type`)
and the number of inputs to `func` are equal.
Parameters
----------
input_type : List[DataType]
func : callable
Returns
-------
inspect.Signature
"""
funcsig = signature(func)
declared_parameter_count = len(input_type)
function_parameter_count = parameter_count(funcsig)
if declared_parameter_count != function_parameter_count:
raise TypeError(
'Function signature {!r} has {:d} parameters, '
'input_type has {:d}. These must match'.format(
func.__name__,
function_parameter_count,
declared_parameter_count,
)
)
return funcsig
class udf:
@staticmethod
def elementwise(input_type, output_type):
"""Define a UDF (user-defined function) that operates element wise on a
Pandas Series.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
length of this list must match the number of arguments to the
function. Variadic arguments are not yet supported.
output_type : ibis.expr.datatypes.DataType
The return type of the function.
Examples
--------
>>> import ibis
>>> import ibis.expr.datatypes as dt
>>> from ibis.pandas.udf import udf
>>> @udf.elementwise(input_type=[dt.string], output_type=dt.int64)
... def my_string_length(series):
... return series.str.len() * 2
"""
input_type = list(map(dt.dtype, input_type))
output_type = dt.dtype(output_type)
def wrapper(func):
# validate that the input_type argument and the function signature
# match
funcsig = valid_function_signature(input_type, func)
# generate a new custom node
UDFNode = type(
func.__name__,
(ops.ValueOp,),
{
'signature': sig.TypeSignature.from_dtypes(input_type),
'output_type': output_type.column_type,
},
)
# definitions
# Define an execution rule for elementwise operations on a
# grouped Series
nargs = len(input_type)
group_by_signatures = [
udf_signature(input_type, pin=pin, klass=SeriesGroupBy)
for pin in range(nargs)
]
@toolz.compose(
*(
execute_node.register(UDFNode, *types)
for types in group_by_signatures
)
)
def execute_udf_node_groupby(op, *args, **kwargs):
groupers = [
grouper
for grouper in (
getattr(arg, 'grouper', None) for arg in args
)
if grouper is not None
]
# all grouping keys must be identical
assert all(groupers[0] == grouper for grouper in groupers[1:])
# we're performing a scalar operation on grouped column, so
# perform the operation directly on the underlying Series
# and regroup after it's finished
arguments = [getattr(arg, 'obj', arg) for arg in args]
groupings = groupers[0].groupings
args, kwargs = arguments_from_signature(
signature(func), *arguments, **kwargs
)
return func(*args, **kwargs).groupby(groupings)
# Define an execution rule for a simple elementwise Series
# function
@execute_node.register(
UDFNode, *udf_signature(input_type, pin=None, klass=pd.Series)
)
@execute_node.register(
UDFNode,
*(
rule_to_python_type(argtype) + nullable(argtype)
for argtype in input_type
),
)
def execute_udf_node(op, *args, **kwargs):
args, kwargs = arguments_from_signature(
funcsig, *args, **kwargs
)
return func(*args, **kwargs)
@functools.wraps(func)
def wrapped(*args):
return UDFNode(*args).to_expr()
return wrapped
return wrapper
@staticmethod
def reduction(input_type, output_type):
"""Define a user-defined reduction function that takes N pandas Series
or scalar values as inputs and produces one row of output.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
length of this list must match the number of arguments to the
function. Variadic arguments are not yet supported.
output_type : ibis.expr.datatypes.DataType
The return type of the function.
Examples
--------
>>> import ibis
>>> import ibis.expr.datatypes as dt
>>> from ibis.pandas.udf import udf
>>> @udf.reduction(input_type=[dt.string], output_type=dt.int64)
... def my_string_length_agg(series, **kwargs):
... return (series.str.len() * 2).sum()
"""
return udf._grouped(
input_type,
output_type,
base_class=ops.Reduction,
output_type_method=operator.attrgetter('scalar_type'),
)
@staticmethod
def analytic(input_type, output_type):
"""Define an *analytic* user-defined function that takes N
pandas Series or scalar values as inputs and produces N rows of output.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
length of this list must match the number of arguments to the
function. Variadic arguments are not yet supported.
output_type : ibis.expr.datatypes.DataType
The return type of the function.
Examples
--------
>>> import ibis
>>> import ibis.expr.datatypes as dt
>>> from ibis.pandas.udf import udf
>>> @udf.analytic(input_type=[dt.double], output_type=dt.double)
... def zscore(series): # note the use of aggregate functions
... return (series - series.mean()) / series.std()
"""
return udf._grouped(
input_type,
output_type,
base_class=ops.AnalyticOp,
output_type_method=operator.attrgetter('column_type'),
)
@staticmethod
def _grouped(input_type, output_type, base_class, output_type_method):
"""Define a user-defined function that is applied per group.
Parameters
----------
input_type : List[ibis.expr.datatypes.DataType]
A list of the types found in :mod:`~ibis.expr.datatypes`. The
length of this list must match the number of arguments to the
function. Variadic arguments are not yet supported.
output_type : ibis.expr.datatypes.DataType
The return type of the function.
base_class : Type[T]
The base class of the generated Node
output_type_method : Callable
A callable that determines the method to call to get the expression
type of the UDF
See Also
--------
ibis.pandas.udf.reduction
ibis.pandas.udf.analytic
"""
input_type = list(map(dt.dtype, input_type))
output_type = dt.dtype(output_type)
def wrapper(func):
funcsig = valid_function_signature(input_type, func)
UDAFNode = type(
func.__name__,
(base_class,),
{
'signature': sig.TypeSignature.from_dtypes(input_type),
'output_type': output_type_method(output_type),
},
)
# An execution rule for a simple aggregate node
@execute_node.register(
UDAFNode, *udf_signature(input_type, pin=None, klass=pd.Series)
)
def execute_udaf_node(op, *args, **kwargs):
args, kwargs = arguments_from_signature(
funcsig, *args, **kwargs
)
return func(*args, **kwargs)
# An execution rule for a grouped aggregation node. This
# includes aggregates applied over a window.
nargs = len(input_type)
group_by_signatures = [
udf_signature(input_type, pin=pin, klass=SeriesGroupBy)
for pin in range(nargs)
]
@toolz.compose(
*(
execute_node.register(UDAFNode, *types)
for types in group_by_signatures
)
)
def execute_udaf_node_groupby(op, *args, **kwargs):
# construct a generator that yields the next group of data
# for every argument excluding the first (pandas performs
# the iteration for the first argument) for each argument
# that is a SeriesGroupBy.
#
# If the argument is not a SeriesGroupBy then keep
# repeating it until all groups are exhausted.
aggcontext = kwargs.pop('aggcontext', None)
assert aggcontext is not None, 'aggcontext is None'
iters = (
(data for _, data in arg)
if isinstance(arg, SeriesGroupBy)
else itertools.repeat(arg)
for arg in args[1:]
)
funcsig = signature(func)
def aggregator(first, *rest, **kwargs):
# map(next, *rest) gets the inputs for the next group
# TODO: might be inefficient to do this on every call
args, kwargs = arguments_from_signature(
funcsig, first, *map(next, rest), **kwargs
)
return func(*args, **kwargs)
result = aggcontext.agg(args[0], aggregator, *iters, **kwargs)
return result
@functools.wraps(func)
def wrapped(*args):
return UDAFNode(*args).to_expr()
return wrapped
return wrapper
| {
"repo_name": "cpcloud/ibis",
"path": "ibis/pandas/udf.py",
"copies": "1",
"size": "17545",
"license": "apache-2.0",
"hash": 2698499249791031000,
"line_mean": 30.3303571429,
"line_max": 79,
"alpha_frac": 0.5628384155,
"autogenerated": false,
"ratio": 4.231789676796913,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 560
} |
"""APIs for discussions"""
from urllib.parse import urljoin
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import redirect
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from discussions.exceptions import (
ChannelAlreadyExistsException,
UnableToAuthenticateDiscussionUserException,
)
from discussions.permissions import CanCreateChannel
from discussions.serializers import ChannelSerializer
from discussions.utils import get_token_for_request
def _set_jwt_cookie(response, token):
"""
Set the token on the response
Args:
response (django.http.Response): the response to set the cookie on
token (str): the JWT token
"""
if not settings.OPEN_DISCUSSIONS_COOKIE_NAME:
raise ImproperlyConfigured('OPEN_DISCUSSIONS_COOKIE_NAME must be set')
response.set_cookie(
settings.OPEN_DISCUSSIONS_COOKIE_NAME,
token,
max_age=settings.OPEN_DISCUSSIONS_JWT_EXPIRES_DELTA,
domain=settings.OPEN_DISCUSSIONS_COOKIE_DOMAIN,
httponly=True
)
@api_view()
def discussions_token(request):
"""
API view for setting discussions JWT token
"""
token = get_token_for_request(request)
if token is not None:
response = Response({
'has_token': True
})
_set_jwt_cookie(response, token)
else:
response = Response({
'has_token': False
}, status=status.HTTP_403_FORBIDDEN)
return response
@login_required
def discussions_redirect(request):
"""
View for setting discussions JWT token and redirecting to discussions
"""
token = get_token_for_request(request, force_create=True)
if token is not None:
response = redirect(urljoin(
settings.OPEN_DISCUSSIONS_REDIRECT_URL, settings.OPEN_DISCUSSIONS_REDIRECT_COMPLETE_URL
))
_set_jwt_cookie(response, token)
else:
raise UnableToAuthenticateDiscussionUserException("Unable to generate a JWT token for user")
return response
class ChannelsView(APIView):
"""
View for discussions channels. Used to create new channels
"""
authentication_classes = (
SessionAuthentication,
TokenAuthentication,
)
permission_classes = (
IsAuthenticated,
CanCreateChannel,
)
def post(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""Create a new channel"""
serializer = ChannelSerializer(data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
try:
serializer.save()
except ChannelAlreadyExistsException:
return Response(
{"name": "A channel with that name already exists"},
status=status.HTTP_409_CONFLICT,
)
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
)
| {
"repo_name": "mitodl/micromasters",
"path": "discussions/views.py",
"copies": "1",
"size": "3292",
"license": "bsd-3-clause",
"hash": -5373787871409946000,
"line_mean": 29.7663551402,
"line_max": 100,
"alpha_frac": 0.6868165249,
"autogenerated": false,
"ratio": 4.247741935483871,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5434558460383871,
"avg_score": null,
"num_lines": null
} |
"""API specification using OpenAPI"""
import json
import flask
from flask import current_app
import apispec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_rest_api.exceptions import OpenAPIVersionNotSpecified
from .plugins import FlaskPlugin
from .field_converters import uploadfield2properties
def _add_leading_slash(string):
"""Add leading slash to a string if there is None"""
return string if string.startswith('/') else '/' + string
DEFAULT_REQUEST_BODY_CONTENT_TYPE = 'application/json'
DEFAULT_RESPONSE_CONTENT_TYPE = 'application/json'
class DocBlueprintMixin:
"""Extend Api to serve the spec in a dedicated blueprint."""
def _register_doc_blueprint(self):
"""Register a blueprint in the application to expose the spec
Doc Blueprint contains routes to
- json spec file
- spec UI (ReDoc, Swagger UI).
"""
api_url = self._app.config.get('OPENAPI_URL_PREFIX', None)
if api_url is not None:
blueprint = flask.Blueprint(
'api-docs',
__name__,
url_prefix=_add_leading_slash(api_url),
template_folder='./templates',
)
# Serve json spec at 'url_prefix/openapi.json' by default
json_path = self._app.config.get(
'OPENAPI_JSON_PATH', 'openapi.json')
blueprint.add_url_rule(
_add_leading_slash(json_path),
endpoint='openapi_json',
view_func=self._openapi_json)
self._register_redoc_rule(blueprint)
self._register_swagger_ui_rule(blueprint)
self._app.register_blueprint(blueprint)
def _register_redoc_rule(self, blueprint):
"""Register ReDoc rule
The ReDoc script URL can be specified as OPENAPI_REDOC_URL.
Otherwise, a CDN script is used based on the ReDoc version. The
version can - and should - be specified as OPENAPI_REDOC_VERSION,
otherwise, 'latest' is used.
When using 1.x branch (i.e. when OPENAPI_REDOC_VERSION is "latest" or
begins with "v1"), GitHub CDN is used.
When using 2.x branch (i.e. when OPENAPI_REDOC_VERSION is "next" or
begins with "2" or "v2"), unpkg nmp CDN is used.
OPENAPI_REDOC_VERSION is ignored when OPENAPI_REDOC_URL is passed.
"""
redoc_path = self._app.config.get('OPENAPI_REDOC_PATH')
if redoc_path is not None:
redoc_url = self._app.config.get('OPENAPI_REDOC_URL')
if redoc_url is None:
# TODO: default to 'next' when ReDoc 2.0.0 is released.
redoc_version = self._app.config.get(
'OPENAPI_REDOC_VERSION', 'latest')
# latest or v1.x -> Redoc GitHub CDN
if redoc_version == 'latest' or redoc_version.startswith('v1'):
redoc_url = (
'https://rebilly.github.io/ReDoc/releases/'
'{}/redoc.min.js'.format(redoc_version))
# next or 2.x -> unpkg npm CDN
else:
redoc_url = (
'https://cdn.jsdelivr.net/npm/redoc@'
'{}/bundles/redoc.standalone.js'.format(redoc_version))
self._redoc_url = redoc_url
blueprint.add_url_rule(
_add_leading_slash(redoc_path),
endpoint='openapi_redoc',
view_func=self._openapi_redoc)
def _register_swagger_ui_rule(self, blueprint):
"""Register Swagger UI rule
The Swagger UI scripts base URL can be specified as
OPENAPI_SWAGGER_UI_URL.
Otherwise, cdnjs is used. In this case, the Swagger UI version must be
specified as OPENAPI_SWAGGER_UI_VERSION. Versions older than 3.x branch
are not supported.
OPENAPI_SWAGGER_UI_VERSION is ignored when OPENAPI_SWAGGER_UI_URL is
passed.
OPENAPI_SWAGGER_UI_SUPPORTED_SUBMIT_METHODS specifes the methods for
which the 'Try it out!' feature is enabled.
"""
swagger_ui_path = self._app.config.get('OPENAPI_SWAGGER_UI_PATH')
if swagger_ui_path is not None:
swagger_ui_url = self._app.config.get('OPENAPI_SWAGGER_UI_URL')
if swagger_ui_url is None:
swagger_ui_version = self._app.config.get(
'OPENAPI_SWAGGER_UI_VERSION')
if swagger_ui_version is not None:
swagger_ui_url = (
'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/'
'{}/'.format(swagger_ui_version))
if swagger_ui_url is not None:
self._swagger_ui_url = swagger_ui_url
self._swagger_ui_supported_submit_methods = (
self._app.config.get(
'OPENAPI_SWAGGER_UI_SUPPORTED_SUBMIT_METHODS',
['get', 'put', 'post', 'delete', 'options',
'head', 'patch', 'trace'])
)
blueprint.add_url_rule(
_add_leading_slash(swagger_ui_path),
endpoint='openapi_swagger_ui',
view_func=self._openapi_swagger_ui)
def _openapi_json(self):
"""Serve JSON spec file"""
# We don't use Flask.jsonify here as it would sort the keys
# alphabetically while we want to preserve the order.
return current_app.response_class(
json.dumps(self.spec.to_dict(), indent=2),
mimetype='application/json')
def _openapi_redoc(self):
"""Expose OpenAPI spec with ReDoc"""
return flask.render_template(
'redoc.html', title=self._app.name, redoc_url=self._redoc_url)
def _openapi_swagger_ui(self):
"""Expose OpenAPI spec with Swagger UI"""
return flask.render_template(
'swagger_ui.html', title=self._app.name,
swagger_ui_url=self._swagger_ui_url,
swagger_ui_supported_submit_methods=(
self._swagger_ui_supported_submit_methods)
)
class APISpecMixin(DocBlueprintMixin):
"""Add APISpec related features to Api class"""
def _init_spec(
self, *, flask_plugin=None, marshmallow_plugin=None,
extra_plugins=None, openapi_version=None, **options
):
# Plugins
self.flask_plugin = flask_plugin or FlaskPlugin()
self.ma_plugin = marshmallow_plugin or MarshmallowPlugin()
plugins = [self.flask_plugin, self.ma_plugin]
plugins.extend(extra_plugins or ())
# APISpec options
openapi_version = self._app.config.get(
'OPENAPI_VERSION', openapi_version)
if openapi_version is None:
raise OpenAPIVersionNotSpecified(
'The OpenAPI version must be specified, either as '
'"OPENAPI_VERSION" app parameter or as '
'"openapi_version" spec kwarg.')
openapi_major_version = int(openapi_version.split('.')[0])
if openapi_major_version < 3:
base_path = self._app.config.get('APPLICATION_ROOT')
options.setdefault('basePath', base_path)
options.setdefault(
'produces', [DEFAULT_RESPONSE_CONTENT_TYPE, ])
options.setdefault(
'consumes', [DEFAULT_REQUEST_BODY_CONTENT_TYPE, ])
options.update(self._app.config.get('API_SPEC_OPTIONS', {}))
# Instantiate spec
self.spec = apispec.APISpec(
self._app.name,
self._app.config.get('API_VERSION', '1'),
openapi_version=openapi_version,
plugins=plugins,
**options,
)
# Register custom fields in spec
for args in self._fields:
self._register_field(*args)
# Register custom converters in spec
for args in self._converters:
self._register_converter(*args)
# Register Upload field properties function
self.ma_plugin.converter.add_attribute_function(uploadfield2properties)
def register_converter(self, converter, conv_type, conv_format=None):
"""Register custom path parameter converter
:param BaseConverter converter: Converter
Subclass of werkzeug's BaseConverter
:param str conv_type: Parameter type
:param str conv_format: Parameter format (optional)
Example: ::
# Register MongoDB's ObjectId converter in Flask application
app.url_map.converters['objectid'] = ObjectIdConverter
# Register converter in Api
api.register_converter(ObjectIdConverter, 'string', 'ObjectID')
@blp.route('/pets/{objectid:pet_id}')
...
api.register_blueprint(blp)
Once the converter is registered, all paths using it will have
corresponding path parameter documented with the right type and format.
Should be called before registering paths with
:meth:`Blueprint.route <Blueprint.route>`.
"""
self._converters.append((converter, conv_type, conv_format))
# Register converter in spec if app is already initialized
if self.spec is not None:
self._register_converter(converter, conv_type, conv_format)
def _register_converter(self, converter, conv_type, conv_format=None):
self.flask_plugin.register_converter(converter, conv_type, conv_format)
def register_field(self, field, *args):
"""Register custom Marshmallow field
Registering the Field class allows the Schema parser to set the proper
type and format when documenting parameters from Schema fields.
:param Field field: Marshmallow Field class
``*args`` can be:
- a pair of the form ``(type, format)`` to map to
- a core marshmallow field type (then that type's mapping is used)
Examples: ::
# Map to ('string', 'ObjectId') passing type and format
api.register_field(ObjectId, 'string', 'ObjectId')
# Map to ('string') passing type
api.register_field(CustomString, 'string', None)
# Map to ('integer, 'int32') passing a code marshmallow field
api.register_field(CustomInteger, ma.fields.Integer)
Should be called before registering schemas with
:meth:`schema <Api.schema>`.
"""
self._fields.append((field, *args))
# Register field in spec if app is already initialized
if self.spec is not None:
self._register_field(field, *args)
def _register_field(self, field, *args):
self.ma_plugin.map_to_openapi_type(*args)(field)
| {
"repo_name": "Nobatek/flask-rest-api",
"path": "flask_rest_api/spec/__init__.py",
"copies": "1",
"size": "10803",
"license": "mit",
"hash": 4357491691792938000,
"line_mean": 38.8597785978,
"line_max": 79,
"alpha_frac": 0.5957230143,
"autogenerated": false,
"ratio": 4.056327450244086,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 271
} |
API_STAGE = "development"
#import warnings
#warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import json
import boto3
from StringIO import StringIO
import datetime as dt
import tempfile
region_bucket_map = {"us-east-1": "slicematrixio",
"us-west-1": "slicematrixiouswest",
"eu-central-1": "slicematrixioeurope1",
"ap-southeast-1": "slicematrixioasia1"}
region_api_map = {"us-east-1": "ud7p0wre43",
"us-west-1": "4u0pr4ljei",
"eu-central-1": "pozdfzsgae",
"ap-southeast-1": "gbq29whx4l"}
class ConnectIO():
def __init__(self, api_key, region = "us-east-1"):
self.api_key = api_key
self.region = region
self.bucket = region_bucket_map[region]
self.api = region_api_map[region]
self.uploader = Uploader(api_key, self.region, self.bucket, self.api)
def put_df(self, name, dataframe):
self.uploader.put_df(name, dataframe)
def list_files(self):
return self.uploader.list_files()
def create_pipeline(self, name, type, params = {}):
# make post request to pipeline/create
#print("creating the pipeline!")
#print(name)
url = 'https://' + self.api + '.execute-api.' + self.region + '.amazonaws.com/' + API_STAGE + '/pipelines/create'
#print url
headers = {'x-api-key': self.api_key, 'Content-Type': 'application/json'}
body = {'name': name, 'type': type, 'params': params}
r = requests.post(url, verify = False, headers = headers, data=json.dumps(body))
return json.loads(r.text)
def run_pipeline(self, name, model, type = None, dataset = None, matrix_name = None, matrix_type = None, X = None, Y = None, extra_params = {}, memory = "large"):
url = 'https://' + self.api + '.execute-api.' + self.region + '.amazonaws.com/' + API_STAGE + '/pipelines/run'
headers = {'x-api-key': self.api_key, 'Content-Type': 'application/json'}
body = {'name': name, 'model': model, 'memory': memory, 'type': type}
if dataset != None:
body['dataset'] = dataset
else:
body['dataset'] = ""
if matrix_name != None and matrix_type != None:
body['matrix_name'] = matrix_name
body['matrix_type'] = matrix_type
if X != None and Y != None:
body['X'] = X
body['Y'] = Y
for param_key in extra_params.keys():
body[param_key] = extra_params[param_key]
#print body
r = requests.post(url, verify = False, headers = headers, data=json.dumps(body))
return json.loads(r.text)
def call_model(self, model, type, method, extra_params = {}, memory = "large"):
url = 'https://' + self.api + '.execute-api.' + self.region + '.amazonaws.com/' + API_STAGE + '/models/call'
headers = {'x-api-key': self.api_key, 'Content-Type': 'application/json'}
body = {'model': model, 'type': type, 'function': method, 'extra_params': extra_params, 'memory': memory}
r = requests.post(url, verify = False, headers = headers, data=json.dumps(body))
#print r.text
return json.loads(r.text)#[method]
#def delete_pipeline(self, name, type):
#def delete_model(self, model, type):
class Uploader():
def __init__(self, api_key, region, bucket, api):
self.api_key = api_key
self.region = region
self.bucket = bucket
self.api = api
def get_upload_url(self, file_name):
url = 'https://' + self.api + '.execute-api.' + self.region + '.amazonaws.com/' + API_STAGE + '/datasets/authorize'
headers = {'x-api-key': self.api_key, 'Content-Type': 'application/json'}
r = requests.post(url, verify = False, headers = headers, data = json.dumps({'name':file_name}))
return json.loads(r.text)
def put_df(self, name, df):
post = self.get_upload_url(name)
files = {"file": df.to_csv()}
response = requests.post(post["url"], data=post["fields"], files=files)
return response
def list_files(self):
url = 'https://' + self.api + '.execute-api.' + self.region + '.amazonaws.com/' + API_STAGE + '/datasets'
headers = {'x-api-key': self.api_key}
r = requests.get(url, verify = False, headers = headers)
return json.loads(r.text)
| {
"repo_name": "tynano/slicematrixIO-python",
"path": "slicematrixIO/connect.py",
"copies": "1",
"size": "4397",
"license": "mit",
"hash": -2251121646119155700,
"line_mean": 40.0934579439,
"line_max": 164,
"alpha_frac": 0.6176938822,
"autogenerated": false,
"ratio": 3.2911676646706587,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4408861546870659,
"avg_score": null,
"num_lines": null
} |
# apis_v1/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.http import HttpResponse
from exception.models import handle_exception
from follow.models import FOLLOW_IGNORE, FOLLOWING, STOP_FOLLOWING
import json
from organization.models import Organization
from organization.controllers import organization_follow_all
from voter.models import fetch_voter_id_from_voter_device_link, Voter, VoterManager
import wevote_functions.admin
from wevote_functions.functions import is_voter_device_id_valid
logger = wevote_functions.admin.get_logger(__name__)
def organization_count():
organization_count_all = 0
try:
organization_list_all = Organization.objects.all()
organization_count_all = organization_list_all.count()
success = True
# We will want to cache a json file and only refresh it every couple of seconds (so it doesn't become
# a bottle neck as we grow)
except Exception as e:
exception_message = "organizationCount: Unable to count list of Organizations from db."
handle_exception(e, logger=logger, exception_message=exception_message)
success = False
json_data = {
'success': success,
'organization_count': organization_count_all,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def organization_follow(voter_device_id, organization_id=0, organization_we_vote_id=''):
"""
Save that the voter wants to follow this org
:param voter_device_id:
:param organization_id:
:return:
"""
return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,
follow_kind=FOLLOWING)
def organization_stop_following(voter_device_id, organization_id=0, organization_we_vote_id=''):
"""
Save that the voter wants to stop following this org
:param voter_device_id:
:param organization_id:
:return:
"""
return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,
follow_kind=STOP_FOLLOWING)
def organization_follow_ignore(voter_device_id, organization_id=0, organization_we_vote_id=''):
"""
Save that the voter wants to ignore this org
:param voter_device_id:
:param organization_id:
:return:
"""
return organization_follow_all(voter_device_id, organization_id, organization_we_vote_id,
follow_kind=FOLLOW_IGNORE)
def voter_count():
voter_count_all = 0
try:
voter_list_all = Voter.objects.all()
# In future, add a filter to only show voters who have actually done something
# voter_list = voter_list.filter(id=voter_id)
voter_count_all = voter_list_all.count()
success = True
# We will want to cache a json file and only refresh it every couple of seconds (so it doesn't become
# a bottle neck as we grow)
except Exception as e:
exception_message = "voterCount: Unable to count list of Voters from db."
handle_exception(e, logger=logger, exception_message=exception_message)
success = False
json_data = {
'success': success,
'voter_count': voter_count_all,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_retrieve_list_for_api(voter_device_id):
results = is_voter_device_id_valid(voter_device_id)
if not results['success']:
results2 = {
'success': False,
'json_data': results['json_data'],
}
return results2
voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
if voter_id > 0:
voter_manager = VoterManager()
results = voter_manager.retrieve_voter_by_id(voter_id)
if results['voter_found']:
voter_id = results['voter_id']
else:
# If we are here, the voter_id could not be found from the voter_device_id
json_data = {
'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
'success': False,
'voter_device_id': voter_device_id,
}
results = {
'success': False,
'json_data': json_data,
}
return results
if voter_id:
voter_list = Voter.objects.all()
voter_list = voter_list.filter(id=voter_id)
if len(voter_list):
results = {
'success': True,
'voter_list': voter_list,
}
return results
# Trying to mimic the Google Civic error codes scheme
errors_list = [
{
'domain': "TODO global",
'reason': "TODO reason",
'message': "TODO Error message here",
'locationType': "TODO Error message here",
'location': "TODO location",
}
]
error_package = {
'errors': errors_list,
'code': 400,
'message': "Error message here",
}
json_data = {
'error': error_package,
'status': "VOTER_ID_COULD_NOT_BE_RETRIEVED",
'success': False,
'voter_device_id': voter_device_id,
}
results = {
'success': False,
'json_data': json_data,
}
return results
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/controllers.py",
"copies": "1",
"size": "5307",
"license": "bsd-3-clause",
"hash": 2482026599645766700,
"line_mean": 32.3773584906,
"line_max": 109,
"alpha_frac": 0.6195590729,
"autogenerated": false,
"ratio": 3.729444834855938,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9844597693666646,
"avg_score": 0.0008812428178584719,
"num_lines": 159
} |
# apis_v1/documentation_source/activity_comment_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def activity_comment_save_doc_template_values(url_root):
"""
Show documentation about activityCommentSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'statement_text',
'value': 'string', # boolean, integer, long, string
'description': 'A text comment.',
},
{
'name': 'visibility_setting',
'value': 'string', # boolean, integer, long, string
'description': 'Two values are currently supported: \'FRIENDS_ONLY\' or \'SHOW_PUBLIC\'.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "date_created": string,\n' \
' "date_last_changed": string,\n' \
' "date_of_notice": string,\n' \
' "id": integer,\n' \
' "activity_post_id": integer,\n' \
' "kind_of_activity": string,\n' \
' "kind_of_seed": string,\n' \
' "new_positions_entered_count": integer,\n' \
' "position_we_vote_id_list": list,\n' \
' "speaker_name": string,\n' \
' "speaker_organization_we_vote_id": string,\n' \
' "speaker_voter_we_vote_id": string,\n' \
' "speaker_profile_image_url_medium": string,\n' \
' "speaker_profile_image_url_tiny": string,\n' \
' "speaker_twitter_handle": string,\n' \
' "speaker_twitter_followers_count": number,\n' \
' "statement_text": string,\n' \
' "visibility_is_public": boolean,\n' \
'}'
template_values = {
'api_name': 'activityCommentSave',
'api_slug': 'activityCommentSave',
'api_introduction':
"Save a new comment posted to the news feed.",
'try_now_link': 'apis_v1:activityCommentSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/activity_comment_save_doc.py",
"copies": "1",
"size": "3677",
"license": "mit",
"hash": 6458148900902329000,
"line_mean": 40.3146067416,
"line_max": 115,
"alpha_frac": 0.5023116671,
"autogenerated": false,
"ratio": 3.8664563617245005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48687680288245005,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/activity_list_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def activity_list_retrieve_doc_template_values(url_root):
"""
Show documentation about activityListRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'Voters device id',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID',
'description': 'No voter could be found from the voter_device_id',
},
]
try_now_link_variables_dict = {
# 'voter_device_id': '',
}
api_response = '{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "activity_list": list\n' \
' [{\n' \
' "date_created": string,\n' \
' "date_last_changed": string,\n' \
' "date_of_notice": string,\n' \
' "id": integer,\n' \
' "activity_notice_seed_id": integer,\n' \
' "activity_post_id": integer,\n' \
' "kind_of_activity": string,\n' \
' "kind_of_seed": string,\n' \
' "new_positions_entered_count": integer,\n' \
' "position_we_vote_id_list": list,\n' \
' "speaker_name": string,\n' \
' "speaker_organization_we_vote_id": string,\n' \
' "speaker_voter_we_vote_id": string,\n' \
' "speaker_profile_image_url_medium": string,\n' \
' "speaker_profile_image_url_tiny": string,\n' \
' "speaker_twitter_handle": string,\n' \
' "speaker_twitter_followers_count": number,\n' \
' "statement_text": string,\n' \
' "visibility_is_public": boolean,\n' \
' },],\n' \
'}'
template_values = {
'api_name': 'activityListRetrieve',
'api_slug': 'activityListRetrieve',
'api_introduction':
"Retrieve an activity_list that we can display to this voter.",
'try_now_link': 'apis_v1:activityListRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/activity_list_retrieve_doc.py",
"copies": "1",
"size": "3444",
"license": "mit",
"hash": -5434006789622247000,
"line_mean": 40,
"line_max": 115,
"alpha_frac": 0.4854819977,
"autogenerated": false,
"ratio": 3.8480446927374303,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.483352669043743,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/activity_notice_list_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def activity_notice_list_retrieve_doc_template_values(url_root):
"""
Show documentation about activityNoticeListRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'Voters device id',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID',
'description': 'No voter could be found from the voter_device_id',
},
]
try_now_link_variables_dict = {
# 'voter_device_id': '',
}
api_response = '{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "activity_notice_list": list\n' \
' [{\n' \
' "date_last_changed": string,\n' \
' "date_of_notice": string,\n' \
' "id": integer,\n' \
' "kind_of_notice": string,\n' \
' "new_positions_entered_count": integer,\n' \
' "position_we_vote_id_list": list,\n' \
' "speaker_name": string,\n' \
' "speaker_organization_we_vote_id": string,\n' \
' "speaker_voter_we_vote_id": string,\n' \
' "speaker_profile_image_url_medium": string,\n' \
' "speaker_profile_image_url_tiny": string,\n' \
' },],\n' \
'}'
template_values = {
'api_name': 'activityNoticeListRetrieve',
'api_slug': 'activityNoticeListRetrieve',
'api_introduction':
"Retrieve a activity_notice_list that we can display to this voter.",
'try_now_link': 'apis_v1:activityNoticeListRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/activity_notice_list_retrieve_doc.py",
"copies": "1",
"size": "3004",
"license": "mit",
"hash": -5135806786990576000,
"line_mean": 38.5263157895,
"line_max": 115,
"alpha_frac": 0.5073235686,
"autogenerated": false,
"ratio": 3.797724399494311,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4805047968094311,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/activity_post_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def activity_post_save_doc_template_values(url_root):
"""
Show documentation about activityPostSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'statement_text',
'value': 'string', # boolean, integer, long, string
'description': 'A text comment.',
},
{
'name': 'visibility_setting',
'value': 'string', # boolean, integer, long, string
'description': 'Two values are currently supported: \'FRIENDS_ONLY\' or \'SHOW_PUBLIC\'.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "date_created": string,\n' \
' "date_last_changed": string,\n' \
' "date_of_notice": string,\n' \
' "id": integer,\n' \
' "activity_post_id": integer,\n' \
' "kind_of_activity": string,\n' \
' "kind_of_seed": string,\n' \
' "new_positions_entered_count": integer,\n' \
' "position_we_vote_id_list": list,\n' \
' "speaker_name": string,\n' \
' "speaker_organization_we_vote_id": string,\n' \
' "speaker_voter_we_vote_id": string,\n' \
' "speaker_profile_image_url_medium": string,\n' \
' "speaker_profile_image_url_tiny": string,\n' \
' "speaker_twitter_handle": string,\n' \
' "speaker_twitter_followers_count": number,\n' \
' "statement_text": string,\n' \
' "visibility_is_public": boolean,\n' \
'}'
template_values = {
'api_name': 'activityPostSave',
'api_slug': 'activityPostSave',
'api_introduction':
"Save a new comment posted to the news feed.",
'try_now_link': 'apis_v1:activityPostSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/activity_post_save_doc.py",
"copies": "1",
"size": "3659",
"license": "mit",
"hash": 892841979047443100,
"line_mean": 40.1123595506,
"line_max": 115,
"alpha_frac": 0.4998633506,
"autogenerated": false,
"ratio": 3.847528916929548,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4847392267529548,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/all_ballot_items_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def all_ballot_items_retrieve_doc_template_values(url_root):
"""
Show documentation about allBallotItemsRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique identifier for a particular election. If not provided, use the most recent '
'ballot for the voter\'s address.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for one state.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'A valid voter_id was not found from voter_device_id. Cannot proceed.',
},
{
'code': 'MISSING_GOOGLE_CIVIC_ELECTION_ID',
'description': 'A valid google_civic_election_id not found. Cannot proceed.',
},
{
'code': 'VOTER_BALLOT_ITEMS_RETRIEVED',
'description': 'Ballot items were found.',
},
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "ballot_found": integer,\n' \
' "ballot_item_list": list\n' \
' [\n' \
' "ballot_item_display_name": string,\n' \
' "candidate_list": list (if kind_of_ballot_item is CANDIDATE)\n' \
' [\n' \
' "we_vote_id": string,\n' \
' "ballot_item_display_name": string,\n' \
' "ballotpedia_candidate_summary": string,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "candidate_photo_url_medium": string,\n' \
' "candidate_photo_url_tiny": string,\n' \
' "kind_of_ballot_item": string,\n' \
' "party": string,\n' \
' "state_code": string,\n' \
' "twitter_handle": string,\n' \
' "twitter_description": string,\n' \
' "twitter_followers_count": integer,\n' \
' "withdrawn_from_election": boolean,\n' \
' "withdrawal_date": string,\n' \
' ],\n' \
' "election_name": string,\n' \
' "election_day_text": string,\n' \
' "google_civic_election_id": integer,\n' \
' "kind_of_ballot_item": string (if kind_of_ballot_item is MEASURE),\n' \
' "measure_subtitle": string (if kind_of_ballot_item is MEASURE)\n' \
' "measure_text": string (if kind_of_ballot_item is MEASURE)\n' \
' "measure_url": string (if kind_of_ballot_item is MEASURE)\n' \
' "no_vote_description": string (if kind_of_ballot_item is MEASURE)\n' \
' "state_code": string,\n' \
' "yes_vote_description": string (if kind_of_ballot_item is MEASURE)\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'allBallotItemsRetrieve',
'api_slug': 'allBallotItemsRetrieve',
'api_introduction':
"Request a skeleton of ballot data for this election, so that the web_app has all of the ids "
"it needs to make more requests for data about each ballot item.",
'try_now_link': 'apis_v1:allBallotItemsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/all_ballot_items_retrieve_doc.py",
"copies": "1",
"size": "5230",
"license": "mit",
"hash": -3778206638191163400,
"line_mean": 45.6964285714,
"line_max": 116,
"alpha_frac": 0.4871892925,
"autogenerated": false,
"ratio": 3.842762674504041,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9823152674588294,
"avg_score": 0.0013598584831496022,
"num_lines": 112
} |
# apis_v1/documentation_source/analytics_action_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def analytics_action_sync_out_doc_template_values(url_root):
"""
Show documentation about analyticsActionSyncOut
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server. '
'If not provided, a new voter_device_id (and voter entry) '
'will be generated, and the voter_device_id will be returned.',
},
]
optional_query_parameter_list = [
{
'name': 'starting_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'The earliest date for the batch we are retrieving. Format: YYYYMMDD (ex/ 20200131) '
'(Default is 3 months ago)',
},
{
'name': 'ending_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'Retrieve data through this date. Format: YYYYMMDD (ex/ 20200228) (Default is right now.)'
},
{
'name': 'return_csv_format',
'value': 'boolean', # boolean, integer, long, string
'description': 'If set to true, return results in CSV format instead of JSON.'
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "id": integer,\n' \
' "action_constant": string,\n' \
' "action_constant_text": string,\n' \
' "authentication_failed_twice": string,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "date_as_integer": integer,\n' \
' "exact_time": string,\n' \
' "first_visit_today": boolean,\n' \
' "google_civic_election_id": string,\n' \
' "is_bot": boolean,\n' \
' "is_desktop": boolean,\n' \
' "is_mobile": boolean,\n' \
' "is_signed_in": boolean,\n' \
' "is_tablet": boolean,\n' \
' "organization_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "user_agent": string,\n' \
' "voter_we_vote_id": string,\n' \
'}]'
template_values = {
'api_name': 'analyticsActionSyncOut',
'api_slug': 'analyticsActionSyncOut',
'api_introduction':
"Allow people with Analytics Admin authority to retrieve raw Analytics Action information "
"for data analysis purposes. The definitions of the ACTION constants ('action_constant') are here: "
"https://github.com/wevote/WeVoteServer/blob/develop/analytics/models.py",
'try_now_link': 'apis_v1:analyticsActionSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/analytics_action_sync_out_doc.py",
"copies": "1",
"size": "3928",
"license": "mit",
"hash": -499998828328813400,
"line_mean": 43.6363636364,
"line_max": 118,
"alpha_frac": 0.5211303462,
"autogenerated": false,
"ratio": 3.924075924075924,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49452062702759236,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/ballot_item_highlights_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_item_highlights_retrieve_doc_template_values(url_root):
"""
Show documentation about ballotItemHighlightsRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "highlight_list": list [\n' \
' {\n' \
' "name": string,\n' \
' "we_vote_id": string,\n' \
' "prior": integer, (\'1\' if from a prior election)\n'\
' }\n' \
' ],\n' \
' "never_highlight_on": list [\n' \
' "*.wevote.us",\n' \
' "api.wevoteusa.org",\n' \
' "localhost"\n' \
' ]\n' \
'}'
template_values = {
'api_name': 'ballotItemHighlightsRetrieve',
'api_slug': 'ballotItemHighlightsRetrieve',
'api_introduction':
"Retrieve all of the candidates that might be highlighted on an endorsement guide. ",
'try_now_link': 'apis_v1:ballotItemHighlightsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/ballot_item_highlights_retrieve_doc.py",
"copies": "1",
"size": "2199",
"license": "mit",
"hash": -3801060857729798000,
"line_mean": 36.2711864407,
"line_max": 115,
"alpha_frac": 0.5093224193,
"autogenerated": false,
"ratio": 3.758974358974359,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9764832440294338,
"avg_score": 0.0006928675960042172,
"num_lines": 59
} |
# apis_v1/documentation_source/ballot_item_options_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_item_options_retrieve_doc_template_values(url_root):
"""
Show documentation about ballotItemOptionsRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique identifier for a particular election. If NOT provided, we instead use the '
'google_civic_election_id for the person who is signed in.',
},
]
optional_query_parameter_list = [
{
'name': 'search_string',
'value': 'string', # boolean, integer, long, string
'description': 'Search words to use to find the candidate or measure for voter guide.'
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'The us state we want ballot item options for. '
},
]
potential_status_codes_list = [
{
'code': 'CANDIDATES_RETRIEVED OFFICES_RETRIEVED MEASURES_RETRIEVED',
'description': 'Ballot items were found.',
},
{
'code': 'NO_CANDIDATES_RETRIEVED NO_OFFICES_RETRIEVED NO_MEASURES_RETRIEVED',
'description': 'Candidates, offices or measures were not able to be retrieved.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "search_string": string,\n' \
' "ballot_item_list": candidate list\n' \
' [\n' \
' "kind_of_ballot_item": string (CANDIDATE),\n' \
' "id": integer,\n' \
' "we_vote_id": string,\n' \
' "ballot_item_display_name": string,\n' \
' "candidate_photo_url_large": string,\n' \
' "candidate_photo_url_medium": string,\n' \
' "candidate_photo_url_tiny": string,\n' \
' "order_on_ballot": integer,\n' \
' "google_civic_election_id": integer,\n' \
' "ballotpedia_candidate_id": integer,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "ballotpedia_person_id": integer,\n' \
' "maplight_id": integer,\n' \
' "contest_office_id": integer,\n' \
' "contest_office_we_vote_id": string,\n' \
' "contest_office_name": string,\n' \
' "politician_id": integer,\n' \
' "politician_we_vote_id": string,\n' \
' "party": string,\n' \
' "ocd_division_id": string,\n' \
' "state_code": string,\n' \
' "candidate_url": string,\n' \
' "candidate_contact_form_url": string, \n' \
' "facebook_url": string,\n' \
' "twitter_url": string,\n' \
' "twitter_handle": string,\n' \
' "google_plus_url": string,\n' \
' "youtube_url": string,\n' \
' "candidate_email": string,\n' \
' "candidate_phone": string,\n' \
' ],\n' \
' "ballot_item_list": measure list\n' \
' [\n' \
' "kind_of_ballot_item": string (MEASURE),\n' \
' "id": integer,\n' \
' "we_vote_id": string,\n' \
' "google_civic_election_id": integer,\n' \
' "ballot_item_display_name": string,\n' \
' "measure_subtitle": string,\n' \
' "maplight_id": integer,\n' \
' "vote_smart_id": string,\n' \
' "measure_text": string,\n' \
' "measure_url": string,\n' \
' "ocd_division_id": string,\n' \
' "district_name": string,\n' \
' "state_code": string,\n' \
' "google_civic_election_id": integer,\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'ballotItemOptionsRetrieve',
'api_slug': 'ballotItemOptionsRetrieve',
'api_introduction':
"Returns measures and candidates based on search terms, so we can help "
"volunteers or staff find offices, candidates or measures when they are building out organizational "
"voter guides. This information is not organized in a "
"hierarchy, but is instead provided in a simple list for browser-side "
"quick search features.",
'try_now_link': 'apis_v1:ballotItemOptionsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/ballot_item_options_retrieve_doc.py",
"copies": "1",
"size": "6318",
"license": "mit",
"hash": -3863076275349608400,
"line_mean": 46.8636363636,
"line_max": 115,
"alpha_frac": 0.4686609687,
"autogenerated": false,
"ratio": 3.9120743034055727,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48807352721055725,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/ballot_item_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_item_retrieve_doc_template_values(url_root):
"""
Show documentation about ballotItemRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'What is the type of ballot item that we are retrieving? '
'(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this ballot_item '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both. '
'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)',
},
{
'name': 'ballot_item_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this ballot_item across all networks '
'(either ballot_item_id OR ballot_item_we_vote_id required -- not both.) '
'NOTE: In the future we might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_we_vote_id': 'wv01cand1755',
}
# See api_response_notes below. This is a wrapper for candidateRetrieve, measureRetrieve and officeRetrieve.
api_response = ""
template_values = {
'api_name': 'ballotItemRetrieve',
'api_slug': 'ballotItemRetrieve',
'api_introduction':
"Retrieve detailed information about one candidate.",
'try_now_link': 'apis_v1:ballotItemRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"This API endpoint is a wrapper for <a href='/apis/v1/docs/officeRetrieve/'>officeRetrieve</a>, "
"<a href='/apis/v1/docs/candidateRetrieve/'>candidateRetrieve</a> and "
"<a href='/apis/v1/docs/measureRetrieve/'>measureRetrieve</a>, . "
"See those endpoints for a description of variables returned.",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/ballot_item_retrieve_doc.py",
"copies": "3",
"size": "3535",
"license": "bsd-3-clause",
"hash": 1708840812524117200,
"line_mean": 44.3205128205,
"line_max": 115,
"alpha_frac": 0.5717114569,
"autogenerated": false,
"ratio": 3.871851040525739,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0017931492005084171,
"num_lines": 78
} |
# apis_v1/documentation_source/ballot_items_search_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_items_search_retrieve_doc_template_values(url_root):
"""
Show documentation about ballotItemsSearchRetrieve: NOT FULLY IMPLEMENTED - see ballotItemOptionsRetrieve instead
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique identifier for a particular election. If not provided, use the most recent '
'ballot for the voter\'s address.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for one state.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'A valid voter_id was not found from voter_device_id. Cannot proceed.',
},
{
'code': 'MISSING_GOOGLE_CIVIC_ELECTION_ID',
'description': 'A valid google_civic_election_id not found. Cannot proceed.',
},
{
'code': 'VOTER_BALLOT_ITEMS_RETRIEVED',
'description': 'Ballot items were found.',
},
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "ballot_found": integer,\n' \
' "ballot_item_list": list\n' \
' [\n' \
' "ballot_item_display_name": string,\n' \
' "candidate_list": list (if kind_of_ballot_item is CANDIDATE)\n' \
' [\n' \
' "we_vote_id": string,\n' \
' "ballot_item_display_name": string,\n' \
' "ballotpedia_candidate_summary": string,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "candidate_photo_url_medium": string,\n' \
' "candidate_photo_url_tiny": string,\n' \
' "kind_of_ballot_item": string,\n' \
' "party": string,\n' \
' "state_code": string,\n' \
' "twitter_handle": string,\n' \
' "twitter_description": string,\n' \
' "twitter_followers_count": integer,\n' \
' "withdrawn_from_election": boolean,\n' \
' "withdrawal_date": string,\n' \
' ],\n' \
' "election_name": string,\n' \
' "election_day_text": string,\n' \
' "google_civic_election_id": integer,\n' \
' "kind_of_ballot_item": string (if kind_of_ballot_item is MEASURE),\n' \
' "measure_subtitle": string (if kind_of_ballot_item is MEASURE)\n' \
' "measure_text": string (if kind_of_ballot_item is MEASURE)\n' \
' "measure_url": string (if kind_of_ballot_item is MEASURE)\n' \
' "no_vote_description": string (if kind_of_ballot_item is MEASURE)\n' \
' "state_code": string,\n' \
' "yes_vote_description": string (if kind_of_ballot_item is MEASURE)\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'ballotItemsSearchRetrieve',
'api_slug': 'ballotItemsSearchRetrieve',
'api_introduction':
"Request a skeleton of ballot data for this election, so that the web_app has all of the ids "
"it needs to make more requests for data about each ballot item.",
'try_now_link': 'apis_v1:ballotItemsSearchRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/ballot_items_search_retrieve_doc.py",
"copies": "1",
"size": "5311",
"license": "mit",
"hash": -1901455732847314700,
"line_mean": 46.4196428571,
"line_max": 117,
"alpha_frac": 0.4933157597,
"autogenerated": false,
"ratio": 3.859738372093023,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4853054131793023,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/ballot_items_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_items_sync_out_doc_template_values(url_root):
"""
Show documentation about ballotItemsSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the ballot_items retrieved to those for this google_civic_election_id. '
'At least one of these variables is needed'
' so we do not overwhelm the API server. ',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'The us state the ballot item is for. At least one of these variables is needed'
' so we do not overwhelm the API server. '
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "we_vote_id": string,\n' \
' "ballot_item_display_name": string,\n' \
' "contest_office_we_vote_id": string,\n' \
' "contest_measure_we_vote_id": string,\n' \
' "google_ballot_placement": string,\n' \
' "google_civic_election_id": string,\n' \
' "state_code": string,\n' \
' "local_ballot_order": string,\n' \
' "measure_subtitle": string,\n' \
' "measure_text": string,\n' \
' "measure_url": string,\n' \
' "no_vote_description": string,\n' \
' "polling_location_we_vote_id": string,\n' \
' "yes_vote_description": string,\n' \
'}]'
template_values = {
'api_name': 'ballotItemsSyncOut',
'api_slug': 'ballotItemsSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:ballotItemsSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/ballot_items_sync_out_doc.py",
"copies": "2",
"size": "2552",
"license": "mit",
"hash": 6089575072113673000,
"line_mean": 38.875,
"line_max": 108,
"alpha_frac": 0.5023510972,
"autogenerated": false,
"ratio": 3.7309941520467835,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5233345249246784,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/ballot_returned_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def ballot_returned_sync_out_doc_template_values(url_root):
"""
Show documentation about ballotReturnedSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the ballot_returned entries retrieved to those for this google_civic_election_id.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the ballot_returned entries retrieved to those in a particular state.',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = '[{\n' \
' "election_date": string,\n' \
' "election_description_text": string,\n' \
' "google_civic_election_id": string,\n' \
' "state_code": string,\n' \
' "latitude": string,\n' \
' "longitude": string,\n' \
' "normalized_line1": string,\n' \
' "normalized_line2": string,\n' \
' "normalized_city": string,\n' \
' "normalized_state": string,\n' \
' "normalized_zip": string,\n' \
' "polling_location_we_vote_id": string,\n' \
' "text_for_map_search": string,\n' \
'}]'
template_values = {
'api_name': 'ballotReturnedSyncOut',
'api_slug': 'ballotReturnedSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:ballotReturnedSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/ballot_returned_sync_out_doc.py",
"copies": "2",
"size": "2298",
"license": "mit",
"hash": 5692286390411458000,
"line_mean": 36.6721311475,
"line_max": 118,
"alpha_frac": 0.5134899913,
"autogenerated": false,
"ratio": 3.7796052631578947,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5293095254457895,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/campaign_follow_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_follow_doc_template_values(url_root):
"""
Show documentation about campaignFollow
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'campaignx_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for the campaignx that the voter wants to support.',
},
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # boolean, integer, long, string
# 'description': '',
# },
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'campaignFollow',
'api_slug': 'campaignFollow',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignFollowView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_follow_doc.py",
"copies": "1",
"size": "2687",
"license": "mit",
"hash": -977698929311042800,
"line_mean": 34.3552631579,
"line_max": 115,
"alpha_frac": 0.5094901377,
"autogenerated": false,
"ratio": 3.9169096209912535,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9923264152977369,
"avg_score": 0.0006271211427767029,
"num_lines": 76
} |
# apis_v1/documentation_source/campaign_list_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_list_retrieve_doc_template_values(url_root):
"""
Show documentation about campaignListRetrieve (No CDN)
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'campaignx_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "campaignx_list": list\n' \
' [\n' \
' "campaign_description": string,\n' \
' "campaign_title": string,\n' \
' "campaignx_we_vote_id": string,\n' \
' "final_election_date_as_integer": integer,\n' \
' "final_election_date_in_past": boolean,\n' \
' "in_draft_mode": boolean,\n' \
' "is_blocked_by_we_vote": boolean,\n' \
' "is_blocked_by_we_vote_reason": string,\n' \
' "is_supporters_count_minimum_exceeded": boolean,\n' \
' "seo_friendly_path": string,\n' \
' "supporters_count": integer,\n' \
' "supporters_count_next_goal": integer,\n' \
' "supporters_count_victory_goal": integer,\n' \
' "visible_on_this_site": boolean,\n' \
' "voter_is_campaignx_owner": boolean,\n' \
' "voter_signed_in_with_email": boolean,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_campaign_photo_large_url": string,\n' \
' "we_vote_hosted_campaign_photo_medium_url": string,\n' \
' "we_vote_hosted_campaign_photo_small_url": string,\n' \
' "campaignx_owner_list": list\n' \
' [\n' \
' "organization_name": string,\n' \
' "organization_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' "visible_to_public": boolean,\n' \
' ],\n' \
' "campaignx_politician_list": list\n' \
' [\n' \
' "campaignx_politician_id": integer,\n' \
' "politician_name": string,\n' \
' "politician_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "we_vote_hosted_profile_image_url_large": string,\n' \
' "we_vote_hosted_profile_image_url_medium": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' ],\n' \
' "campaignx_politician_list_exists": boolean,\n' \
' "campaignx_politician_starter_list": list\n' \
' [\n' \
' "value": string,\n' \
' "label": string,\n' \
' ],\n' \
' "seo_friendly_path_list": list\n' \
' [],\n' \
' ],\n' \
' "campaign_list_found": boolean,\n' \
' "promoted_campaignx_we_vote_ids": list [],\n' \
' "voter_started_campaignx_we_vote_ids": list [],\n' \
' "voter_supported_campaignx_we_vote_ids": list [],\n' \
'}'
template_values = {
'api_name': 'campaignListRetrieve',
'api_slug': 'campaignListRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignListRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_list_retrieve_doc.py",
"copies": "1",
"size": "5318",
"license": "mit",
"hash": -5573113656177673000,
"line_mean": 46.0619469027,
"line_max": 115,
"alpha_frac": 0.4539300489,
"autogenerated": false,
"ratio": 3.724089635854342,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9672538845154406,
"avg_score": 0.0010961679199871757,
"num_lines": 113
} |
# apis_v1/documentation_source/campaign_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_retrieve_doc_template_values(url_root):
"""
Show documentation about campaignRetrieve (CDN) & campaignRetrieveAsOwner (No CDN)
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'campaignx_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique id of the campaign.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'campaignx_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "campaign_description": string,\n' \
' "campaign_title": string,\n' \
' "campaignx_politician_list_exists": boolean,\n' \
' "campaignx_we_vote_id": string,\n' \
' "final_election_date_as_integer": integer,\n' \
' "final_election_date_in_past": boolean,\n' \
' "in_draft_mode": boolean,\n' \
' "is_blocked_by_we_vote": boolean,\n' \
' "is_blocked_by_we_vote_reason": string,\n' \
' "is_supporters_count_minimum_exceeded": boolean,\n' \
' "organization_we_vote_id": string,\n' \
' "seo_friendly_path": string,\n' \
' "supporters_count": integer,\n' \
' "supporters_count_next_goal": integer,\n' \
' "supporters_count_victory_goal": integer,\n' \
' "visible_on_this_site": boolean,\n' \
' "voter_is_campaignx_owner": boolean,\n' \
' "voter_signed_in_with_email": boolean,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_campaign_photo_large_url": string,\n' \
' "we_vote_hosted_campaign_photo_medium_url": string,\n' \
' "we_vote_hosted_campaign_photo_small_url": string,\n' \
' "campaignx_owner_list": list\n' \
' [\n' \
' "organization_name": string,\n' \
' "organization_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' "visible_to_public": boolean,\n' \
' ],\n' \
' "campaignx_politician_list": list\n' \
' [\n' \
' "campaignx_politician_id": integer,\n' \
' "politician_name": string,\n' \
' "politician_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "we_vote_hosted_profile_image_url_large": string,\n' \
' "we_vote_hosted_profile_image_url_medium": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' ],\n' \
' "campaignx_politician_starter_list": list\n' \
' [\n' \
' "value": string,\n' \
' "label": string,\n' \
' ],\n' \
' "latest_campaignx_supporter_endorsement_list": list\n' \
' [\n' \
' "id": integer,\n' \
' "date_supported": string,\n' \
' "organization_we_vote_id": string,\n' \
' "supporter_endorsement": string,\n' \
' "supporter_name": string,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' ],\n' \
' "latest_campaignx_supporter_list": list\n' \
' [\n' \
' "id": integer,\n' \
' "date_supported": string,\n' \
' "organization_we_vote_id": string,\n' \
' "supporter_endorsement": string,\n' \
' "supporter_name": string,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
' ],\n' \
' "seo_friendly_path_list": list\n' \
' [],\n' \
'}'
template_values = {
'api_name': 'campaignRetrieve',
'api_slug': 'campaignRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_retrieve_doc.py",
"copies": "1",
"size": "6198",
"license": "mit",
"hash": -3912782342938946600,
"line_mean": 45.9545454545,
"line_max": 115,
"alpha_frac": 0.4503065505,
"autogenerated": false,
"ratio": 3.693682955899881,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46439895063998804,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/campaign_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_save_doc_template_values(url_root):
"""
Show documentation about campaignSave & campaignStartSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'campaignx_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The we_vote_id for the campaign.',
},
{
'name': 'campaign_title',
'value': 'string', # boolean, integer, long, string
'description': 'The title of the campaign.',
},
{
'name': 'campaign_title_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the campaign\'s title?',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'campaignx_we_vote_id': 'wv85camp1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "campaign_title": string,\n' \
' "in_draft_mode": boolean,\n' \
' "campaignx_we_vote_id": string,\n' \
' "organization_we_vote_id": string,\n' \
' "voter_we_vote_id": string,\n' \
'}'
template_values = {
'api_name': 'campaignSave',
'api_slug': 'campaignSave',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'POST',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_save_doc.py",
"copies": "1",
"size": "3030",
"license": "mit",
"hash": -7337227193971249000,
"line_mean": 36.4074074074,
"line_max": 115,
"alpha_frac": 0.5095709571,
"autogenerated": false,
"ratio": 3.889602053915276,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4899173011015276,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/campaign_supporter_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_supporter_retrieve_doc_template_values(url_root):
"""
Show documentation about campaignSupporterRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'campaignx_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The we_vote_id for the campaign.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'campaignx_we_vote_id': 'wv85camp1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "supporter_endorsement": string,\n' \
' "supporter_name": string,\n' \
' "campaignx_we_vote_id": string,\n' \
' "date_last_changed": string,\n' \
' "date_supported": string,\n' \
' "organization_we_vote_id": string,\n' \
' "visible_to_public": boolean,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
'}'
template_values = {
'api_name': 'campaignSupporterRetrieve',
'api_slug': 'campaignSupporterRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignSupporterRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_supporter_retrieve_doc.py",
"copies": "1",
"size": "2915",
"license": "mit",
"hash": -4449842327457139700,
"line_mean": 37.8666666667,
"line_max": 115,
"alpha_frac": 0.522813036,
"autogenerated": false,
"ratio": 3.8154450261780104,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.483825806217801,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/campaign_supporter_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def campaign_supporter_save_doc_template_values(url_root):
"""
Show documentation about campaignSupporterSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'campaignx_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The we_vote_id for the campaign.',
},
{
'name': 'voter_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The voter_we_vote_id for the supporter.',
},
]
optional_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The organization_we_vote_id for the supporter.',
},
{
'name': 'supporter_name',
'value': 'string', # boolean, integer, long, string
'description': 'The title of the campaign.',
},
{
'name': 'supporter_name_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the campaign\'s title?',
},
{
'name': 'supporter_endorsement',
'value': 'string', # boolean, integer, long, string
'description': 'The title of the campaign.',
},
{
'name': 'supporter_endorsement_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the campaign\'s title?',
},
{
'name': 'visible_to_public',
'value': 'string', # boolean, integer, long, string
'description': 'The title of the campaign.',
},
{
'name': 'visible_to_public_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the campaign\'s title?',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'campaignx_we_vote_id': 'wv85camp1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "campaignx_we_vote_id": string,\n' \
' "date_last_changed": string,\n' \
' "date_supported": string,\n' \
' "organization_we_vote_id": string,\n' \
' "supporter_endorsement": string,\n' \
' "supporter_name": string,\n' \
' "visible_to_public": boolean,\n' \
' "voter_we_vote_id": string,\n' \
' "we_vote_hosted_profile_image_url_tiny": string,\n' \
'}'
template_values = {
'api_name': 'campaignSupporterSave',
'api_slug': 'campaignSupporterSave',
'api_introduction':
"",
'try_now_link': 'apis_v1:campaignSupporterSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/campaign_supporter_save_doc.py",
"copies": "1",
"size": "4554",
"license": "mit",
"hash": -3086231619119143400,
"line_mean": 38.6,
"line_max": 115,
"alpha_frac": 0.5035133948,
"autogenerated": false,
"ratio": 3.9496964440589766,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4953209838858976,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/candidate_list_for_upcoming_elections_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def doc_template_values(url_root):
"""
Show documentation about candidateListForUpcomingElectionsRetrieve
"""
required_query_parameter_list = [
{
'name': 'google_civic_election_id_list[]',
'value': 'integerlist', # boolean, integer, long, string
'description': 'List of election ids we care about.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
'description': 'A valid internal office_id parameter was not included, nor was a office_we_vote_id. '
'Cannot proceed.',
},
{
'code': 'CANDIDATES_RETRIEVED',
'description': 'Candidates were returned for these elections.',
},
{
'code': 'NO_CANDIDATES_RETRIEVED',
'description': 'There are no candidates stored for these elections.',
},
]
try_now_link_variables_dict = {
'google_civic_election_id_list': '6000',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "google_civic_election_id_list": list,\n' \
' [\n' \
' integer,\n' \
' ],\n' \
' "candidate_list": list\n' \
' [\n' \
' "name": string,\n' \
' "we_vote_id": string,\n' \
' "alternate_names": list,\n' \
' [\n' \
' "String here",\n' \
' ],\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'candidateListForUpcomingElectionsRetrieve',
'api_slug': 'candidateListForUpcomingElectionsRetrieve',
'api_introduction':
"Retrieve all of the candidates competing in upcoming offices. "
"This shares the same response package format with measureListForUpcomingElectionsRetrieve.",
'try_now_link': 'apis_v1:candidateListForUpcomingElectionsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/candidate_list_for_upcoming_elections_retrieve_doc.py",
"copies": "1",
"size": "2869",
"license": "mit",
"hash": 7931787893223635000,
"line_mean": 37.2533333333,
"line_max": 114,
"alpha_frac": 0.5130707564,
"autogenerated": false,
"ratio": 3.8304405874499334,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48435113438499333,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/candidate_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def candidate_retrieve_doc_template_values(url_root):
"""
Show documentation about candidateRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'candidate_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this candidate '
'(either candidate_id OR candidate_we_vote_id required -- not both. '
'If it exists, candidate_id is used instead of candidate_we_vote_id)',
},
{
'name': 'candidate_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this candidate across all networks '
'(either candidate_id OR candidate_we_vote_id required -- not both.) '
'NOTE: In the future we might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
'candidate_we_vote_id': 'wv01cand1755',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "ballot_item_display_name": string,\n' \
' "candidate_photo_url_large": string,\n' \
' "candidate_photo_url_medium": string,\n' \
' "candidate_photo_url_tiny": string,\n' \
' "ballotpedia_candidate_id": integer,\n' \
' "ballotpedia_candidate_summary": string,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "ballotpedia_person_id": integer,\n' \
' "candidate_email": string,\n' \
' "candidate_phone": string,\n' \
' "contest_office_id": integer,\n' \
' "contest_office_we_vote_id": string,\n' \
' "contest_office_name": string,\n' \
' "candidate_url": string,\n' \
' "candidate_contact_form_url": string,\n' \
' "facebook_url": string,\n' \
' "google_civic_election_id": integer,\n' \
' "id": integer,\n' \
' "kind_of_ballot_item": string (CANDIDATE),\n' \
' "last_updated": string (time in this format %Y-%m-%d %H:%M:%S),\n' \
' "maplight_id": integer,\n' \
' "ocd_division_id": string,\n' \
' "order_on_ballot": integer,\n' \
' "politician_id": integer,\n' \
' "politician_we_vote_id": string,\n' \
' "party": string,\n' \
' "state_code": string,\n' \
' "twitter_url": string,\n' \
' "twitter_handle": string,\n' \
' "twitter_description": string,\n' \
' "twitter_followers_count": integer,\n' \
' "we_vote_id": string,\n' \
' "withdrawn_from_election": boolean,\n' \
' "withdrawal_date": date,\n' \
' "youtube_url": string,\n' \
'}'
template_values = {
'api_name': 'candidateRetrieve',
'api_slug': 'candidateRetrieve',
'api_introduction':
"Retrieve detailed information about one candidate.",
'try_now_link': 'apis_v1:candidateRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/candidate_retrieve_doc.py",
"copies": "1",
"size": "5074",
"license": "mit",
"hash": -3340478527769224000,
"line_mean": 45.1272727273,
"line_max": 115,
"alpha_frac": 0.4897516752,
"autogenerated": false,
"ratio": 3.9151234567901234,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9899788066601563,
"avg_score": 0.001017413077712048,
"num_lines": 110
} |
# apis_v1/documentation_source/candidates_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def candidates_retrieve_doc_template_values(url_root):
"""
Show documentation about candidatesRetrieve
"""
required_query_parameter_list = [
{
'name': 'office_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this office '
'(either office_id OR office_we_vote_id required -- not both. '
'If it exists, office_id is used instead of office_we_vote_id)',
},
{
'name': 'office_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this office across all networks '
'(either office_id OR office_we_vote_id required -- not both.) NOTE: In the future we '
'might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
'description': 'A valid internal office_id parameter was not included, nor was a office_we_vote_id. '
'Cannot proceed.',
},
{
'code': 'CANDIDATES_RETRIEVED',
'description': 'Candidates were returned for this Office.',
},
{
'code': 'NO_CANDIDATES_RETRIEVED',
'description': 'There are no candidates stored for this Office.',
},
]
try_now_link_variables_dict = {
'office_we_vote_id': 'wv01off922',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "office_id": integer,\n' \
' "office_we_vote_id": string,\n' \
' "google_civic_election_id": integer,\n' \
' "candidate_list": list\n' \
' [\n' \
' "id": integer,\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "ballot_item_display_name": string,\n' \
' "ballotpedia_candidate_id": integer,\n' \
' "ballotpedia_candidate_summary": string,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "candidate_photo_url_large": string,\n' \
' "candidate_photo_url_medium": string,\n'\
' "candidate_photo_url_tiny": string,\n' \
' "kind_of_ballot_item": string,\n' \
' "last_updated": string (time in this format %Y-%m-%d %H:%M:%S),\n' \
' "order_on_ballot": integer,\n' \
' "party": string,\n' \
' "we_vote_id": string,\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'candidatesRetrieve',
'api_slug': 'candidatesRetrieve',
'api_introduction':
"Retrieve all of the candidates competing for a particular office.",
'try_now_link': 'apis_v1:candidatesRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/candidates_retrieve_doc.py",
"copies": "1",
"size": "3927",
"license": "mit",
"hash": 5229742567141294000,
"line_mean": 42.1538461538,
"line_max": 115,
"alpha_frac": 0.4871403107,
"autogenerated": false,
"ratio": 3.899702085402185,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9882176284396594,
"avg_score": 0.0009332223411180066,
"num_lines": 91
} |
# apis_v1/documentation_source/candidates_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def candidates_sync_out_doc_template_values(url_root):
"""
Show documentation about candidatesSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the candidates retrieved to those for this google_civic_election_id.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the candidates entries retrieved to those in a particular state.',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = '[{\n' \
' "ballot_guide_official_statement": string,\n' \
' "ballotpedia_candidate_id": integer,\n' \
' "ballotpedia_candidate_name": string,\n' \
' "ballotpedia_candidate_summary": string,\n' \
' "ballotpedia_candidate_url": string,\n' \
' "ballotpedia_election_id": integer,\n' \
' "ballotpedia_image_id": integer,\n' \
' "ballotpedia_office_id": integer,\n' \
' "ballotpedia_page_title": string,\n' \
' "ballotpedia_person_id": integer,\n' \
' "ballotpedia_photo_url": string,\n' \
' "ballotpedia_race_id": integer,\n' \
' "birth_day_text": string,\n' \
' "candidate_email": string,\n' \
' "candidate_gender": string,\n' \
' "candidate_is_incumbent": boolean,\n' \
' "candidate_is_top_ticket": boolean,\n' \
' "candidate_name": string,\n' \
' "candidate_participation_status": string,\n' \
' "candidate_phone": string,\n' \
' "candidate_twitter_handle": string,\n' \
' "candidate_url": string,\n' \
' "candidate_contact_form_url": string,\n' \
' "contest_office_we_vote_id": string,\n' \
' "contest_office_name": string,\n' \
' "crowdpac_candidate_id": integer,\n' \
' "facebook_url": string,\n' \
' "google_civic_candidate_name": string,\n' \
' "google_civic_candidate_name2": string,\n' \
' "google_civic_candidate_name3": string,\n' \
' "google_civic_election_id": integer,\n' \
' "google_plus_url": string,\n' \
' "maplight_id": integer,\n' \
' "ocd_division_id": string,\n' \
' "order_on_ballot": string,\n' \
' "party": string,\n' \
' "photo_url": string,\n' \
' "photo_url_from_maplight": string,\n' \
' "photo_url_from_vote_smart": string,\n' \
' "politician_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "twitter_url": string,\n' \
' "twitter_user_id": string,\n' \
' "twitter_name": string,\n' \
' "twitter_location": string,\n' \
' "twitter_followers_count": integer,\n' \
' "twitter_profile_image_url_https": string,\n' \
' "twitter_description": string,\n' \
' "vote_smart_id": integer,\n' \
' "we_vote_id": string,\n' \
' "wikipedia_page_id": string,\n' \
' "wikipedia_page_title": string,\n' \
' "wikipedia_photo_url": string,\n' \
' "youtube_url": string,\n' \
'}]'
template_values = {
'api_name': 'candidatesSyncOut',
'api_slug': 'candidatesSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:candidatesSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/candidates_sync_out_doc.py",
"copies": "1",
"size": "4698",
"license": "mit",
"hash": 869763949454562000,
"line_mean": 45.0588235294,
"line_max": 105,
"alpha_frac": 0.4650915283,
"autogenerated": false,
"ratio": 3.7050473186119874,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9669195813390773,
"avg_score": 0.0001886067042429254,
"num_lines": 102
} |
# apis_v1/documentation_source/candidate_to_office_link_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def candidate_to_office_link_sync_out_doc_template_values(url_root):
"""
Show documentation about candidateToOfficeLinkSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the candidate_to_office_link entries retrieved '
'to those for this google_civic_election_id.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the candidate_to_office_link entries retrieved to those in a particular state.',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = '[{\n' \
' "candidate_we_vote_id": string,\n' \
' "contest_office_we_vote_id": string,\n' \
' "google_civic_election_id": integer,\n' \
' "state_code": string,\n' \
'}]'
template_values = {
'api_name': 'candidateToOfficeLinkSyncOut',
'api_slug': 'candidateToOfficeLinkSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:candidateToOfficeLinkSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/candidate_to_office_link_sync_out_doc.py",
"copies": "1",
"size": "1910",
"license": "mit",
"hash": 4035975722121712600,
"line_mean": 35.0377358491,
"line_max": 115,
"alpha_frac": 0.5492146597,
"autogenerated": false,
"ratio": 3.7377690802348336,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9785047376580123,
"avg_score": 0.00038727267094215695,
"num_lines": 53
} |
# apis_v1/documentation_source/device_id_generate_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def device_id_generate_doc_template_values(url_root):
"""
Show documentation about deviceIdGenerate
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'deviceIdGenerate',
'api_slug': 'deviceIdGenerate',
'api_introduction':
"Generate a transient unique identifier (voter_device_id - stored on client) "
"which ties the device to a persistent voter_id (mapped together and stored on the server)."
"Note: This call does not create a voter account -- that must be done in voterCreate.",
'try_now_link': 'apis_v1:deviceIdGenerateView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/device_id_generate_doc.py",
"copies": "3",
"size": "1601",
"license": "mit",
"hash": 1903585928250587100,
"line_mean": 37.119047619,
"line_max": 115,
"alpha_frac": 0.5996252342,
"autogenerated": false,
"ratio": 3.7582159624413145,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5857841196641315,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/device_id_generate_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def device_store_firebase_fcm_token_doc_template_values(url_root):
"""
Show documentation about deviceStoreFirebaseCloudMessagingToken
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'platform_type',
'value': 'string', # boolean, integer, long, string
'description': 'One of {"IOS", "ANDROID", WEBAPP"} ',
},
{
'name': 'firebase_fcm_token',
'value': 'string', # boolean, integer, long, string
'description': 'The unique Firebase Cloud Messaging Token assigned to the calling device by Firebase',
},
]
optional_query_parameter_list = [
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "voter_device_id": string (88 characters long),\n' \
' "success": boolean,\n' \
' "status": string,\n'
'}'
template_values = {
'api_name': 'deviceStoreFirebaseCloudMessagingToken',
'api_slug': 'deviceStoreFirebaseCloudMessagingToken',
'api_introduction':
"Store the Firebase Cloud Messaging Token, which has been generated for this device by Google's Firebase"
"cloud service. This token allows WeVote to send a notification to the device via an API call to the"
"Firebase Service. These notifications (in iOS) will appear on screen even if the WeVoteCordova app is not"
"currently running. (Android has different conditions).",
'try_now_link': 'apis_v1:deviceStoreFirebaseCloudMessagingToken',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/device_store_firebase_fcm_token_doc.py",
"copies": "1",
"size": "2610",
"license": "mit",
"hash": -7127808258742012000,
"line_mean": 42.5,
"line_max": 120,
"alpha_frac": 0.5846743295,
"autogenerated": false,
"ratio": 3.907185628742515,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9986693275488779,
"avg_score": 0.001033336550747066,
"num_lines": 60
} |
# apis_v1/documentation_source/_documentation_template.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
# This is a template (starting point) for creating documentation for individual APIs
def PUT_NAME_HERE_doc_template_values(url_root):
"""
Show documentation about voterRetrieve
"""
required_query_parameter_list = [
# {
# 'name': 'voter_device_id',
# 'value': 'string', # boolean, integer, long, string
# 'description': 'An 88 character unique identifier linked to a voter record on the server',
# },
# {
# 'name': 'api_key',
# 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
# 'description': 'The unique key provided to any organization using the WeVoteServer APIs',
# },
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # boolean, integer, long, string
# 'description': '',
# },
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'voterRetrieve - TODO This documentation still in progress',
'api_slug': 'voterRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:voterRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/_documentation_template.py",
"copies": "3",
"size": "2586",
"license": "mit",
"hash": 4162939031492961000,
"line_mean": 34.4246575342,
"line_max": 117,
"alpha_frac": 0.5197215777,
"autogenerated": false,
"ratio": 3.8424962852897475,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5862217862989747,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/donation_with_stripe_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def donation_with_stripe_doc_template_values(url_root):
"""
Show documentation about donationWithStripe
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'token',
'value': 'string', # boolean, integer, long, string
'description': 'A unique identifier linked to a stripe payment made on the client side',
},
{
'name': 'email',
'value': 'string', # boolean, integer, long, string
'description': 'A unique email linked to a stripe payment made on the client side',
},
{
'name': 'donation_amount',
'value': 'integer', # boolean, integer, long, string
'description': 'amount to be charged',
},
{
'name': 'monthly_donation',
'value': 'boolean', # boolean, integer, long, string
'description': 'recurring donation',
},
]
optional_query_parameter_list = [
# {
# 'name': 'amount',
# 'value': 'integer', # boolean, integer, long, string
# 'description': 'amount to be charged',
# },
]
potential_status_codes_list = [
{
'code': 'TOKEN_MISSING',
'description': 'Cannot proceed. A valid stripe token was not included.',
}
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "token": string,\n' \
'}'
template_values = {
'api_name': 'donationWithStripe',
'api_slug': 'donationWithStripe',
'api_introduction':
"Process stripe payment with stripe client generated token",
'try_now_link': 'apis_v1:donationWithStripeView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'POST',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/donation_with_stripe_doc.py",
"copies": "2",
"size": "3042",
"license": "mit",
"hash": -4574584969128191500,
"line_mean": 36.0975609756,
"line_max": 115,
"alpha_frac": 0.5164365549,
"autogenerated": false,
"ratio": 4.013192612137203,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007278770613478268,
"num_lines": 82
} |
# apis_v1/documentation_source/elections_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def elections_retrieve_doc_template_values(url_root):
"""
Show documentation about electionsRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "election_list": list,\n' \
' [{\n' \
' "ballot_location_list": list\n' \
' [{\n' \
' "ballot_location_display_name": string,\n' \
' "ballot_location_shortcut": string,\n' \
' "ballot_returned_we_vote_id": string,\n' \
' "ballot_location_order": integer,\n' \
' }],\n' \
' "google_civic_election_id": integer,\n' \
' "election_name": string,\n' \
' "election_day_text": string,\n' \
' "election_is_upcoming": boolean,\n' \
' "get_election_state": string,\n' \
' "state_code": string,\n' \
' "ocd_division_id": string,\n' \
' "state_code_list": list\n' \
' [],\n' \
' }]\n'\
'}'
template_values = {
'api_name': 'electionsRetrieve',
'api_slug': 'electionsRetrieve',
'api_introduction':
"Return a list of all elections, and include ballot location options so a voter can jump to "
"sample ballots.",
'try_now_link': 'apis_v1:electionsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/elections_retrieve_doc.py",
"copies": "1",
"size": "2744",
"license": "mit",
"hash": 6567108115151647000,
"line_mean": 38.768115942,
"line_max": 115,
"alpha_frac": 0.4788629738,
"autogenerated": false,
"ratio": 3.8324022346368714,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9808556601596379,
"avg_score": 0.0005417213680983426,
"num_lines": 69
} |
# apis_v1/documentation_source/elections_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def elections_sync_out_doc_template_values(url_root):
"""
Show documentation about electionsSyncOut
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = 'SUCCESS:\n'\
'[{\n' \
' "google_civic_election_id": integer,\n' \
' "election_name": string,\n' \
' "election_day_text": string,\n' \
' "get_election_state": string,\n' \
' "ocd_division_id": string,\n' \
' "include_in_list_for_voters": boolean,\n' \
'}]\n'\
'FAILURE:\n'\
'{\n' \
' "status": string,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'electionsSyncOut',
'api_slug': 'electionsSyncOut',
'api_introduction':
"Export the raw elections data stored in the database to JSON format. "
"This API call does not reach out to the Google Civic API, but simply returns data that was retrieved "
"earlier.",
'try_now_link': 'apis_v1:electionsSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"NOTE: Success returns a single entry in a json list, "
"so you need to loop through that list to get to the single election entry.",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/elections_sync_out_doc.py",
"copies": "2",
"size": "2497",
"license": "mit",
"hash": 2544682974262196000,
"line_mean": 38.6349206349,
"line_max": 115,
"alpha_frac": 0.529835803,
"autogenerated": false,
"ratio": 3.8415384615384616,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009457361080266686,
"num_lines": 63
} |
# apis_v1/documentation_source/email_ballot_data_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def email_ballot_data_doc_template_values(url_root):
"""
Show documentation about emailBallotData
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'email_address_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of Email address for self or friends to send the ballot link to.',
},
{
'name': 'first_name_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of First Name for self or friends to send the ballot link to.',
},
{
'name': 'last_name_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of Last Name for self or friends to send the ballot link to.',
},
{
'name': 'email_addresses_raw',
'value': 'string', # boolean, integer, long, string
'description': 'Email addresses to send the ballot link to.',
},
{
'name': 'ballot_link',
'value': 'string', # boolean, integer, long, string
'description': 'Ballot link to send.',
},
]
optional_query_parameter_list = [
{
'name': 'invitation_message',
'value': 'string', # boolean, integer, long, string
'description': 'An optional message to send.',
},
{
'name': 'sender_email_address',
'value': 'string', # boolean, integer, long, string
'description': 'The email address to use if an email is not attached to voter account.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "description_of_send_status": string,\n' \
'}'
template_values = {
'api_name': 'emailBallotData',
'api_slug': 'emailBallotData',
'api_introduction':
"Send current ballot link via email to self or friends.",
'try_now_link': 'apis_v1:emailBallotDataView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/email_ballot_data_doc.py",
"copies": "2",
"size": "3818",
"license": "mit",
"hash": -5429811578026439000,
"line_mean": 37.9591836735,
"line_max": 115,
"alpha_frac": 0.5170246202,
"autogenerated": false,
"ratio": 4.027426160337553,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5544450780537553,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/facebook_disconnect_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def facebook_disconnect_doc_template_values(url_root):
"""
Show documentation about facebookDisconnect
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'facebookDisconnect',
'api_slug': 'facebookDisconnect',
'api_introduction':
"",
'try_now_link': 'apis_v1:facebookDisconnectView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/facebook_disconnect_doc.py",
"copies": "3",
"size": "2301",
"license": "mit",
"hash": 2315311794173355500,
"line_mean": 33.8636363636,
"line_max": 115,
"alpha_frac": 0.5310734463,
"autogenerated": false,
"ratio": 3.886824324324324,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005764518520552243,
"num_lines": 66
} |
# apis_v1/documentation_source/facebook_friends_action_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def facebook_friends_action_doc_template_values(url_root):
"""
Show documentation about facebookFriendsAction
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = []
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'facebookFriendsAction',
'api_slug': 'facebookFriendsAction',
'api_introduction':
"This will provide list of facebook friends who are using wevote app.",
'try_now_link': 'apis_v1:facebookFriendsActionView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/facebook_friends_action_doc.py",
"copies": "2",
"size": "2291",
"license": "mit",
"hash": -473836297853697700,
"line_mean": 36.5573770492,
"line_max": 115,
"alpha_frac": 0.5591444784,
"autogenerated": false,
"ratio": 3.850420168067227,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5409564646467226,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/facebook_sign_in_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def facebook_sign_in_doc_template_values(url_root):
"""
Show documentation about facebookSignIn
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'facebook_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The Facebook big integer id',
},
{
'name': 'facebook_email',
'value': 'string', # boolean, integer, long, string
'description': 'Email address from Facebook',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "facebook_id": integer,\n' \
' "facebook_email": string,\n' \
'}'
template_values = {
'api_name': 'facebookSignIn',
'api_slug': 'facebookSignIn',
'api_introduction':
"",
'try_now_link': 'apis_v1:facebookSignInView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/facebook_sign_in_doc.py",
"copies": "1",
"size": "2777",
"license": "bsd-3-clause",
"hash": 43409404100121030,
"line_mean": 34.6025641026,
"line_max": 115,
"alpha_frac": 0.5066618653,
"autogenerated": false,
"ratio": 3.9057665260196908,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49124283913196903,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/friend_invitation_by_email_send_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_email_send_doc_template_values(url_root):
"""
Show documentation about friendInvitationByEmailSend
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'email_address_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of Email address for friends to send the invitation to.',
},
{
'name': 'first_name_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of First Name for friends to send the invitation to.',
},
{
'name': 'last_name_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of Last Name for friends to send the invitation to.',
},
{
'name': 'email_addresses_raw',
'value': 'string', # boolean, integer, long, string
'description': 'Email addresses to send the invitation to.',
},
]
optional_query_parameter_list = [
{
'name': 'invitation_message',
'value': 'string', # boolean, integer, long, string
'description': 'An optional message to send.',
},
{
'name': 'sender_email_address',
'value': 'string', # boolean, integer, long, string
'description': 'The email address to use if an email is not attached to voter account.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "description_of_send_status": string,\n' \
'}'
template_values = {
'api_name': 'friendInvitationByEmailSend',
'api_slug': 'friendInvitationByEmailSend',
'api_introduction':
"Invite your friends via email.",
'try_now_link': 'apis_v1:friendInvitationByEmailSendView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_by_email_send_doc.py",
"copies": "2",
"size": "3653",
"license": "mit",
"hash": -3260672754217835000,
"line_mean": 38.7065217391,
"line_max": 115,
"alpha_frac": 0.5291541199,
"autogenerated": false,
"ratio": 4.03646408839779,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.556561820829779,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/friend_invitation_by_email_verify_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_email_verify_doc_template_values(url_root):
"""
Show documentation about friendInvitationByEmailVerify
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'invitation_secret_key',
'value': 'string', # boolean, integer, long, string
'description': 'We pass in the secret key as an identifier.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'MISSING_VOTER_ID_OR_ADDRESS_TYPE',
'description': 'Cannot proceed. Missing variables voter_id or address_type while trying to save.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "email_ownership_is_verified": boolean,\n' \
' "email_secret_key_belongs_to_this_voter": boolean,\n' \
' "email_address_found": boolean,\n' \
'}'
template_values = {
'api_name': 'friendInvitationByEmailVerify',
'api_slug': 'friendInvitationByEmailVerify',
'api_introduction':
"Accept an invitation to be someone's friend based on a secret key.",
'try_now_link': 'apis_v1:friendInvitationByEmailVerifyView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_by_email_verify_doc.py",
"copies": "2",
"size": "2814",
"license": "mit",
"hash": 7977120746514978000,
"line_mean": 39.2,
"line_max": 115,
"alpha_frac": 0.5554371002,
"autogenerated": false,
"ratio": 3.860082304526749,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008452787945062248,
"num_lines": 70
} |
# apis_v1/documentation_source/friend_invitation_by_facebook_send_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_facebook_send_doc_template_values(url_root):
"""
Show documentation about friendInvitationByFacebookSend
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'recipients_facebook_id_array',
'value': 'integer', # boolean, integer, long, string
'description': 'Array of recipients facebook id to send the invitation to.',
},
{
'name': 'recipients_facebook_name_array',
'value': 'string', # boolean, integer, long, string
'description': 'Array of facebook name for friends to send the invitation to.',
},
{
'name': 'facebook_request_id',
'value': 'integer', # boolean, integer, long, string
'description': 'facebook request id for the invitation.',
},
]
optional_query_parameter_list = []
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "all_friends_facebook_link_created_results": string,\n' \
'}'
template_values = {
'api_name': 'friendInvitationByFacebookSend',
'api_slug': 'friendInvitationByFacebookSend',
'api_introduction':
"Invite your friends via facebook.",
'try_now_link': 'apis_v1:friendInvitationByFacebookSendView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_by_facebook_send_doc.py",
"copies": "2",
"size": "2930",
"license": "mit",
"hash": -4508523324656641000,
"line_mean": 37.0519480519,
"line_max": 108,
"alpha_frac": 0.5686006826,
"autogenerated": false,
"ratio": 3.927613941018767,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007921632891627892,
"num_lines": 77
} |
# apis_v1/documentation_source/friend_invitation_by_facebook_verify_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_facebook_verify_doc_template_values(url_root):
"""
Show documentation about friendInvitationByFacebookVerify
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'facebook_request_id',
'value': 'integer', # boolean, integer, long, string
'description': 'facebook request id for the invitation.',
},
{
'name': 'recipient_facebook_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Recipient facebook id to verify the invitation.',
},
{
'name': 'sender_facebook_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Sender facebook id to verify the invitation.',
},
]
optional_query_parameter_list = []
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "invitation_found": boolean,\n' \
'}'
template_values = {
'api_name': 'friendInvitationByFacebookVerify',
'api_slug': 'friendInvitationByFacebookVerify',
'api_introduction':
"Accept an invitation from facebook to be someone's friend",
'try_now_link': 'apis_v1:friendInvitationByFacebookVerifyView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_by_facebook_verify_doc.py",
"copies": "2",
"size": "2896",
"license": "mit",
"hash": -2811840169981980700,
"line_mean": 36.6103896104,
"line_max": 108,
"alpha_frac": 0.5666436464,
"autogenerated": false,
"ratio": 3.950886766712142,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005050786102852426,
"num_lines": 77
} |
# apis_v1/documentation_source/friend_invitation_by_we_vote_id_send_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_we_vote_id_send_doc_template_values(url_root):
"""
Show documentation about friendInvitationByWeVoteIdSend
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'other_voter_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The voter to send the friend invitation to.',
},
]
optional_query_parameter_list = [
{
'name': 'invitation_message',
'value': 'string', # boolean, integer, long, string
'description': 'An optional message to send.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "description_of_send_status": string,\n' \
'}'
template_values = {
'api_name': 'friendInvitationByWeVoteIdSend',
'api_slug': 'friendInvitationByWeVoteIdSend',
'api_introduction':
"Invite a friend to be your friend from a 'suggested friends' list.",
'try_now_link': 'apis_v1:friendInvitationByWeVoteIdSendView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_by_we_vote_id_send_doc.py",
"copies": "2",
"size": "2771",
"license": "mit",
"hash": -1510976801737101800,
"line_mean": 37.4861111111,
"line_max": 115,
"alpha_frac": 0.5478166727,
"autogenerated": false,
"ratio": 3.7958904109589042,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006977908914842265,
"num_lines": 72
} |
# apis_v1/documentation_source/friend_invitation_information_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_information_doc_template_values(url_root):
"""
Show documentation about friendInvitationInformation
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'invitation_secret_key',
'value': 'string', # boolean, integer, long, string
'description': 'We pass in the secret key as an identifier.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'MISSING_VOTER_ID_OR_ADDRESS_TYPE',
'description': 'Cannot proceed. Missing variables voter_id or address_type while trying to save.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "friend_first_name": string,\n' \
' "friend_last_name": string,\n' \
' "friend_image_url_https_tiny": string,\n' \
' "friend_issue_we_vote_id_list": list,\n' \
' "friend_we_vote_id": string,\n' \
' "friend_organization_we_vote_id": string,\n' \
' "invitation_found": boolean,\n' \
' "invitation_message": string,\n' \
' "invitation_secret_key": string,\n' \
'}'
template_values = {
'api_name': 'friendInvitationInformation',
'api_slug': 'friendInvitationInformation',
'api_introduction':
"Accept an invitation to be someone's friend based on a secret key.",
'try_now_link': 'apis_v1:friendInvitationInformationView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invitation_information_doc.py",
"copies": "1",
"size": "3134",
"license": "mit",
"hash": 9023239233887531000,
"line_mean": 40.2368421053,
"line_max": 115,
"alpha_frac": 0.5366943204,
"autogenerated": false,
"ratio": 3.8883374689826304,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9921139058092141,
"avg_score": 0.0007785462580978388,
"num_lines": 76
} |
# apis_v1/documentation_source/friend_invite_response_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invite_response_doc_template_values(url_root):
"""
Show documentation about friendInviteResponse
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'kind_of_invite_response',
'value': 'string', # boolean, integer, long, string
'description': 'Default is ACCEPT_INVITATION. '
'Other options include DELETE_INVITATION_EMAIL_SENT_BY_ME, '
'DELETE_INVITATION_VOTER_SENT_BY_ME, IGNORE_INVITATION, UNFRIEND_CURRENT_FRIEND.',
},
{
'name': 'voter_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for the voter who sent the invitation.',
},
{
'name': 'recipient_voter_email',
'value': 'string', # boolean, integer, long, string
'description': 'The email address the invitation was sent to (when a recipient we_vote_id could not '
'be found.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
'kind_of_invite_response': 'ACCEPT_INVITATION',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_we_vote_id": string,\n' \
' "kind_of_invite_response": string, \n' \
' "friend_voter": dict\n' \
' {\n' \
' "voter_we_vote_id": string,\n' \
' "voter_display_name": string,\n' \
' "voter_photo_url": string,\n' \
' "voter_twitter_handle": string,\n' \
' "voter_twitter_description": string,\n' \
' "voter_twitter_followers_count": number,\n' \
' "voter_state_code": string,\n' \
' },\n' \
'}'
template_values = {
'api_name': 'friendInviteResponse',
'api_slug': 'friendInviteResponse',
'api_introduction':
"Respond to friend request. ",
'try_now_link': 'apis_v1:friendInviteResponseView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_invite_response_doc.py",
"copies": "2",
"size": "3789",
"license": "mit",
"hash": -4463780854671962000,
"line_mean": 40.6373626374,
"line_max": 115,
"alpha_frac": 0.5054103985,
"autogenerated": false,
"ratio": 3.8663265306122447,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5371736929112245,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/friend_list_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_list_doc_template_values(url_root):
"""
Show documentation about friendList
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'kind_of_list',
'value': 'string', # boolean, integer, long, string
'description': 'Default is CURRENT_FRIENDS. '
'Other options include FRIEND_INVITATIONS_PROCESSED, '
'FRIEND_INVITATIONS_SENT_TO_ME, FRIEND_INVITATIONS_SENT_BY_ME, '
'FRIEND_INVITATIONS_WAITING_FOR_VERIFICATION, FRIENDS_IN_COMMON, '
'IGNORED_FRIEND_INVITATIONS, or SUGGESTED_FRIEND_LIST.',
},
]
optional_query_parameter_list = [
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Only show friends who live in this state.'
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
'kind_of_list': 'CURRENT_FRIENDS',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "count": integer,\n' \
' "voter_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "kind_of_list": string, \n' \
' "friend_list": list\n' \
' [\n' \
' "voter_we_vote_id": string,\n' \
' "voter_display_name": string,\n' \
' "voter_photo_url_large": string,\n' \
' "voter_photo_url_medium": string,\n' \
' "voter_photo_url_tiny": string,\n' \
' "voter_email_address": string,\n' \
' "voter_twitter_handle": string,\n' \
' "voter_twitter_description": string,\n' \
' "voter_twitter_followers_count": number,\n' \
' "linked_organization_we_vote_id": string,\n' \
' "voter_state_code": string,\n' \
' "invitation_status": string,\n' \
' "invitation_sent_to": string,\n' \
' "positions_taken": number,\n' \
' "mutual_friends": number,\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'friendList',
'api_slug': 'friendList',
'api_introduction':
"Request information about a voter's friends, including invitations to become a friend, "
"a list of current friends, and friends you share in common with another voter.",
'try_now_link': 'apis_v1:friendListView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_list_doc.py",
"copies": "1",
"size": "4261",
"license": "mit",
"hash": 1444219918554994400,
"line_mean": 42.4795918367,
"line_max": 115,
"alpha_frac": 0.4874442619,
"autogenerated": false,
"ratio": 3.8146821844225602,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9796841755287277,
"avg_score": 0.0010569382070568026,
"num_lines": 98
} |
# apis_v1/documentation_source/friend_lists_all_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_lists_all_doc_template_values(url_root):
"""
Show documentation about friendListsAll
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Only show friends who live in this state.'
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "count": integer,\n' \
' "voter_we_vote_id": string,\n' \
' "state_code": string,\n' \
' "current_friends": list\n' \
' "invitations_processed": list\n' \
' "invitations_sent_to_me": list\n' \
' "invitations_sent_by_me": list\n' \
' "invitations_waiting_for_verify": list\n' \
' "suggested_friends": list\n' \
'}'
template_values = {
'api_name': 'friendListsAll',
'api_slug': 'friendListsAll',
'api_introduction':
"Request information about a voter's friends, including invitations to become a friend, "
"a list of current friends, and friends you share in common with another voter. This API differs from friendList in that it "
"returns six different lists at once.",
'try_now_link': 'apis_v1:friendListsAllView',
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/friend_lists_all_doc.py",
"copies": "1",
"size": "2926",
"license": "mit",
"hash": 4498508388568941600,
"line_mean": 39.6388888889,
"line_max": 138,
"alpha_frac": 0.525290499,
"autogenerated": false,
"ratio": 3.9170013386880855,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9924580449604156,
"avg_score": 0.003542277616785955,
"num_lines": 72
} |
# apis_v1/documentation_source/issue_descriptions_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issue_descriptions_retrieve_doc_template_values(url_root):
"""
Show documentation about issueDescriptionsRetrieve
"""
optional_query_parameter_list = [
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "issue_description": string,\n' \
' "issue_icon_local_path": string,\n' \
' "issue_image_url": string,\n' \
' "issue_photo_url_large": string,\n' \
' "issue_photo_url_medium": string,\n' \
' "issue_photo_url_tiny": string,\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issueDescriptionsRetrieve',
'api_slug': 'issueDescriptionsRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:issueDescriptionsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issue_descriptions_retrieve_doc.py",
"copies": "1",
"size": "1741",
"license": "mit",
"hash": 8978101055952310000,
"line_mean": 33.82,
"line_max": 71,
"alpha_frac": 0.4974152786,
"autogenerated": false,
"ratio": 3.7121535181236673,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9709568796723668,
"avg_score": 0,
"num_lines": 50
} |
# apis_v1/documentation_source/issue_follow_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issue_follow_doc_template_values(url_root):
"""
Show documentation about issueFollow
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'issue_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for the issue that the voter wants to follow.',
},
{
'name': 'follow',
'value': 'boolean', # boolean, integer, long, string
'description': 'Voter wants to follow or stop following this issue.',
},
{
'name': 'ignore',
'value': 'boolean', # boolean, integer, long, string
'description': 'Voter wants to ignore this issue.',
},
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # boolean, integer, long, string
# 'description': '',
# },
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
'}'
template_values = {
'api_name': 'issueFollow',
'api_slug': 'issueFollow',
'api_introduction':
"",
'try_now_link': 'apis_v1:issueFollowView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issue_follow_doc.py",
"copies": "2",
"size": "3072",
"license": "mit",
"hash": -6527028708349916000,
"line_mean": 34.7209302326,
"line_max": 115,
"alpha_frac": 0.4964192708,
"autogenerated": false,
"ratio": 3.9741267787839587,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5470546049583959,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_followed_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_followed_retrieve_doc_template_values(url_root):
"""
Show documentation about issuesFollowedRetrieve
"""
optional_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "is_issue_followed": boolean,\n' \
' "is_issue_ignored": boolean,\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issuesFollowedRetrieve',
'api_slug': 'issuesFollowedRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesFollowedRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_followed_retrieve_doc.py",
"copies": "1",
"size": "1702",
"license": "mit",
"hash": -7241087734314464000,
"line_mean": 32.3725490196,
"line_max": 102,
"alpha_frac": 0.5129259694,
"autogenerated": false,
"ratio": 3.7161572052401746,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47290831746401746,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_linked_to_organization_doc_template_values(url_root):
"""
Show documentation about issuesLinkedToOrganization
"""
optional_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The Endorser\'s we vote id',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "organization_we_vote_id": string,\n'\
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "issue_description": string,\n' \
' "issue_photo_url_large": string,\n' \
' "issue_photo_url_medium": string,\n' \
' "issue_photo_url_tiny": string,\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issuesLinkedToOrganization',
'api_slug': 'issuesLinkedToOrganization',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesLinkedToOrganizationView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_linked_to_organization_doc.py",
"copies": "1",
"size": "1866",
"license": "mit",
"hash": 1062331184821039200,
"line_mean": 33.5555555556,
"line_max": 71,
"alpha_frac": 0.4994640943,
"autogenerated": false,
"ratio": 3.7245508982035926,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47240149925035924,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_retrieve_doc_template_values(url_root):
"""
Show documentation about issuesRetrieve
"""
optional_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'sort_formula',
'value': 'string', # boolean, integer, long, string
'description': 'Default is MOST_LINKED_ORGANIZATIONS '
'A string constant that specifies the criteria which will be used to sort the issues. '
'Other options are: ALPHABETICAL_ASCENDING',
},
{
'name': 'voter_issues_only',
'value': 'boolean', # boolean, integer, long, string
'description': 'DEPRECATED When this is true, then the resulting issue list contains only issues followed '
'by this voter\'s we vote id',
},
{
'name': 'include_voter_follow_status',
'value': 'boolean', # boolean, integer, long, string
'description': 'When this is true, then the fields: is_issue_followed and is_issue_ignored reflect the '
'real values, else these fields are false by default',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'sort_formula': 'MOST_LINKED_ORGANIZATIONS',
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "voter_issues_only": boolean DEPRECATED, \n' \
' "include_voter_follow_status": boolean, \n' \
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "issue_description": string,\n' \
' "issue_icon_local_path": string,\n' \
' "issue_image_url": string,\n' \
' "issue_photo_url_large": string,\n' \
' "issue_photo_url_medium": string,\n' \
' "issue_photo_url_tiny": string,\n' \
' "is_issue_followed": boolean,\n' \
' "is_issue_ignored": boolean,\n' \
' ],\n' \
' "issue_score_list": list DEPRECATED\n' \
' [\n' \
' "ballot_item_we_vote_id": string,\n' \
' "issue_support_score": integer,\n' \
' "issue_oppose_score": integer,\n' \
' "organization_we_vote_id_support_list": list\n' \
' [\n' \
' "organization_we_vote_id": string,\n' \
' ],\n' \
' "organization_name_support_list": list\n' \
' [\n' \
' "Speaker Display Name": string,\n' \
' ],\n' \
' "organization_we_vote_id_oppose_list": list\n' \
' [\n' \
' "organization_we_vote_id": string,\n' \
' ],\n' \
' "organization_name_oppose_list": list\n' \
' [\n' \
' "Speaker Display Name": string,\n' \
' ],\n' \
' ],\n' \
' "issues_under_ballot_items_list": list\n' \
' [\n' \
' "ballot_item_we_vote_id": string,\n' \
' "issue_we_vote_id_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' ],\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issuesRetrieve',
'api_slug': 'issuesRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_retrieve_doc.py",
"copies": "1",
"size": "4796",
"license": "mit",
"hash": -7849024197543433000,
"line_mean": 43,
"line_max": 120,
"alpha_frac": 0.4305671393,
"autogenerated": false,
"ratio": 3.9279279279279278,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48584950672279276,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_to_link_to_for_organization_doc_template_values(url_root):
"""
Show documentation about issuesToLinkToForOrganization
"""
optional_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The Endorser\'s we vote id',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "organization_we_vote_id": string,\n' \
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "issue_description": string,\n' \
' "issue_photo_url_large": string,\n' \
' "issue_photo_url_medium": string,\n' \
' "issue_photo_url_tiny": string,\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issuesToLinkToForOrganization',
'api_slug': 'issuesToLinkToForOrganization',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesToLinkToForOrganizationView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_to_link_to_for_organization_doc.py",
"copies": "1",
"size": "1884",
"license": "mit",
"hash": 7230866504147912000,
"line_mean": 33.8888888889,
"line_max": 71,
"alpha_frac": 0.5026539278,
"autogenerated": false,
"ratio": 3.6653696498054473,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9668023577605447,
"avg_score": 0,
"num_lines": 54
} |
# apis_v1/documentation_source/issues_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_link_to_issue_doc_template_values(url_root):
"""
Show documentation about organizationLinkToIssue
"""
optional_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The we vote id for the Endorser',
},
{
'name': 'issue_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The we vote id for the Issue',
},
{
'name': 'organization_linked_to_issue',
'value': 'boolean', # boolean, integer, long, string
'description': 'Specifies if the organization to issue link should be active or blocked',
},
{
'name': 'reason_for_link',
'value': 'string', # boolean, integer, long, string
'description': 'The reason why the link is being made active'
'Possible reasons for making link active: NO_REASON, LINKED_BY_ORGANIZATION, '
' LINKED_BY_WE_VOTE, AUTO_LINKED_BY_HASHTAG, AUTO_LINKED_BY_HASHTAG',
},
{
'name': 'reason_for_unlink',
'value': 'string', # boolean, integer, long, string
'description': 'The reason why the link is being blocked or unlinked'
'Possible reasons for making link inactive(blocking the link): BLOCKED_BY_ORGANIZATION, '
'BLOCKED_BY_WE_VOTE, FLAGGED_BY_VOTERS',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'organization_linked_to_issue': 'True',
'reason_for_link': 'LINKED_BY_ORGANIZATION',
'reason_for_unlink': 'BLOCKED_BY_ORGANIZATION',
}
api_response = '[{' \
' "success": boolean,\n' \
' "status": string,\n' \
' "organization_we_vote_id": string,\n' \
' "issue_we_vote_id": string,\n' \
' "organization_linked_to_issue": boolean,\n' \
' "reason_for_link": string,\n' \
' "reason_for_unlink": string,\n' \
' "link_issue_found": boolean,\n' \
' "link_issue": {\n' \
' "organization_we_vote_id": string,\n' \
' "issue_id": integer,\n' \
' "issue_we_vote_id": string,\n' \
' "link_active": boolean,\n' \
' "reason_for_link": string,\n' \
' "link_blocked": boolean,\n' \
' "reason_link_is_blocked": boolean,\n' \
' "}" \n' \
'}]'
template_values = {
'api_name': 'organizationLinkToIssue',
'api_slug': 'organizationLinkToIssue',
'api_introduction':
"",
'try_now_link': 'apis_v1:organizationLinkToIssueView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_link_to_issue_doc.py",
"copies": "1",
"size": "3568",
"license": "mit",
"hash": 7969354435739001000,
"line_mean": 40.488372093,
"line_max": 118,
"alpha_frac": 0.5008408072,
"autogenerated": false,
"ratio": 3.836559139784946,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4837399946984946,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def retrieve_issues_to_follow_doc_template_values(url_root):
"""
Show documentation about retrieveIssuesToFollowDocs
"""
optional_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'sort_formula',
'value': 'string', # boolean, integer, long, string
'description': 'Default is MOST_LINKED_ORGANIZATIONS '
'A string constant that specifies the criteria which will be used to sort the issues. '
'Other options are: ALPHABETICAL_ASCENDING',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'sort_formula': 'MOST_LINKED_ORGANIZATIONS',
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "issue_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' "issue_name": string,\n' \
' "issue_description": string,\n' \
' "issue_photo_url_large": string,\n' \
' "issue_photo_url_medium": string,\n' \
' "issue_photo_url_tiny": string,\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'retrieveIssuesToFollow',
'api_slug': 'retrieveIssuesToFollow',
'api_introduction':
"",
'try_now_link': 'apis_v1:retrieveIssuesToFollowView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/retrieve_issues_to_follow_doc.py",
"copies": "2",
"size": "2290",
"license": "mit",
"hash": -1380089438583744000,
"line_mean": 36.5409836066,
"line_max": 115,
"alpha_frac": 0.503930131,
"autogenerated": false,
"ratio": 3.8230383973288813,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002989520372222464,
"num_lines": 61
} |
# apis_v1/documentation_source/issues_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_sync_out_doc_template_values(url_root):
"""
Show documentation about issuesSyncOut
"""
optional_query_parameter_list = [
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "we_vote_id": string,\n' \
' "issues_name": string,\n' \
' "issues_description": string,\n' \
' "issue_followers_count": integer,\n' \
' "linked_organization_count": integer,\n' \
' "we_vote_hosted_image_url_large": string,\n' \
' "we_vote_hosted_image_url_medium": string,\n' \
' "we_vote_hosted_image_url_tiny": string,\n' \
'}]'
template_values = {
'api_name': 'issuesSyncOut',
'api_slug': 'issuesSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_sync_out_doc.py",
"copies": "2",
"size": "1481",
"license": "mit",
"hash": 8685364467365300000,
"line_mean": 31.9111111111,
"line_max": 71,
"alpha_frac": 0.5273463876,
"autogenerated": false,
"ratio": 3.509478672985782,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5036825060585781,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/issues_under_ballot_items_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def issues_under_ballot_items_retrieve_doc_template_values(url_root):
"""
Show documentation about issuesUnderBallotItemsRetrieve
"""
optional_query_parameter_list = [
{
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "issues_under_ballot_items_list": list\n' \
' [\n' \
' "ballot_item_we_vote_id": string,\n' \
' "issue_we_vote_id_list": list\n' \
' [\n' \
' "issue_we_vote_id": string,\n' \
' ],\n' \
' ],\n' \
'}]'
template_values = {
'api_name': 'issuesUnderBallotItemsRetrieve',
'api_slug': 'issuesUnderBallotItemsRetrieve',
'api_introduction':
"",
'try_now_link': 'apis_v1:issuesUnderBallotItemsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/issues_under_ballot_items_retrieve_doc.py",
"copies": "1",
"size": "1591",
"license": "mit",
"hash": -4281437256716536300,
"line_mean": 31.4693877551,
"line_max": 72,
"alpha_frac": 0.5047140163,
"autogenerated": false,
"ratio": 3.5833333333333335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45880473496333335,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/measure_list_for_upcoming_elections_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def doc_template_values(url_root):
"""
Show documentation about measureListForUpcomingElectionsRetrieve
"""
required_query_parameter_list = [
{
'name': 'google_civic_election_id_list[]',
'value': 'integerlist', # boolean, integer, long, string
'description': 'List of election ids we care about.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
'description': 'A valid internal office_id parameter was not included, nor was a office_we_vote_id. '
'Cannot proceed.',
},
{
'code': 'CANDIDATES_RETRIEVED',
'description': 'Candidates were returned for these elections.',
},
{
'code': 'NO_CANDIDATES_RETRIEVED',
'description': 'There are no candidates stored for these elections.',
},
]
try_now_link_variables_dict = {
'google_civic_election_id_list': '6000',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "google_civic_election_id_list": list\n' \
' [\n' \
' integer,\n' \
' ],\n' \
' "measure_list": list\n' \
' [\n' \
' "ballot_item_display_name": string,\n' \
' "ballot_item_website": string,\n' \
' "candidate_contact_form_url": string,\n' \
' "candidate_we_vote_id": string,\n' \
' "alternate_names": list,\n' \
' [\n' \
' "String here",\n' \
' ],\n' \
' "google_civic_election_id": string,\n' \
' "office_we_vote_id": string,\n' \
' "measure_we_vote_id": string,\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'measureListForUpcomingElectionsRetrieve',
'api_slug': 'measureListForUpcomingElectionsRetrieve',
'api_introduction':
"Retrieve all of the measures in upcoming elections. This shares the same response package format with "
"candidateListForUpcomingElectionsRetrieve.",
'try_now_link': 'apis_v1:measureListForUpcomingElectionsRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/measure_list_for_upcoming_elections_retrieve_doc.py",
"copies": "1",
"size": "3192",
"license": "mit",
"hash": 3495424889469021000,
"line_mean": 38.9,
"line_max": 116,
"alpha_frac": 0.5025062657,
"autogenerated": false,
"ratio": 3.790973871733967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9791649459090717,
"avg_score": 0.00036613566865007413,
"num_lines": 80
} |
# apis_v1/documentation_source/measure_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def measure_retrieve_doc_template_values(url_root):
"""
Show documentation about measureRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'measure_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this measure '
'(either measure_id OR measure_we_vote_id required -- not both. '
'If it exists, measure_id is used instead of measure_we_vote_id)',
},
{
'name': 'measure_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this measure across all networks '
'(either measure_id OR measure_we_vote_id required -- not both. '
'If it exists, measure_id is used instead of measure_we_vote_id)',
},
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # boolean, integer, long, string
# 'description': '',
# },
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
'measure_we_vote_id': 'wv01meas1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "ballot_item_display_name": string,\n' \
' "district_name": string,\n' \
' "election_display_name": string,\n' \
' "google_civic_election_id": integer,\n' \
' "id": integer,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
' "last_updated": string (time in this format %Y-%m-%d %H:%M:%S),\n' \
' "maplight_id": integer,\n' \
' "measure_subtitle": string,\n' \
' "measure_text": string,\n' \
' "measure_url": string,\n' \
' "no_vote_description": string,\n' \
' "ocd_division_id": string,\n' \
' "regional_display_name": string,\n' \
' "state_code": string,\n' \
' "state_display_name": string,\n' \
' "vote_smart_id": string,\n' \
' "we_vote_id": string,\n' \
' "yes_vote_description": string,\n' \
'}'
template_values = {
'api_name': 'measureRetrieve',
'api_slug': 'measureRetrieve',
'api_introduction':
"Retrieve detailed information about one measure.",
'try_now_link': 'apis_v1:measureRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/measure_retrieve_doc.py",
"copies": "1",
"size": "4333",
"license": "mit",
"hash": 6388755428075915000,
"line_mean": 41.067961165,
"line_max": 115,
"alpha_frac": 0.4825755827,
"autogenerated": false,
"ratio": 3.9426751592356686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9920276219039581,
"avg_score": 0.0009949045792174284,
"num_lines": 103
} |
# apis_v1/documentation_source/measures_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def measures_sync_out_doc_template_values(url_root):
"""
Show documentation about measuresSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the measures retrieved to those for this google_civic_election_id.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the measures entries retrieved to those in a particular state.',
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = '[{\n' \
' "we_vote_id": string,\n' \
' "maplight_id": integer,\n' \
' "vote_smart_id": integer,\n' \
' "ballotpedia_page_title": string,\n' \
' "ballotpedia_photo_url": string,\n' \
' "ballotpedia_no_vote_description": string,\n' \
' "ballotpedia_yes_vote_description": string,\n' \
' "district_id": string,\n' \
' "district_name": string,\n' \
' "district_scope": string,\n' \
' "google_civic_election_id": string,\n' \
' "measure_title": string,\n' \
' "measure_subtitle": string,\n' \
' "measure_text": string,\n' \
' "measure_url": string,\n' \
' "ocd_division_id": string,\n' \
' "primary_party": string,\n' \
' "state_code": string,\n' \
' "wikipedia_page_id": string,\n' \
' "wikipedia_page_title": string,\n' \
' "wikipedia_photo_url": string,\n' \
'}]'
template_values = {
'api_name': 'measuresSyncOut',
'api_slug': 'measuresSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:measuresSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/measures_sync_out_doc.py",
"copies": "2",
"size": "2688",
"license": "mit",
"hash": 5273942164279198000,
"line_mean": 37.9565217391,
"line_max": 103,
"alpha_frac": 0.4847470238,
"autogenerated": false,
"ratio": 3.6973865199449794,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5182133543744979,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/office_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def office_retrieve_doc_template_values(url_root):
"""
Show documentation about officeRetrieve
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'office_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this office '
'(either office_id OR office_we_vote_id required -- not both. '
'If it exists, office_id is used instead of office_we_vote_id)',
},
{
'name': 'office_we_vote_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique identifier for this office across all networks '
'(either office_id OR office_we_vote_id required -- not both.) NOTE: In the future we '
'might support other identifiers used in the industry.',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
'office_we_vote_id': 'wv01off922',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
' "id": integer,\n' \
' "we_vote_id": string,\n' \
' "google_civic_election_id": integer,\n' \
' "ballot_item_display_name": string,\n' \
' "ocd_division_id": string,\n' \
' "maplight_id": string,\n' \
' "ballotpedia_id": string,\n' \
' "wikipedia_id": string,\n' \
' "number_voting_for": integer,\n' \
' "number_elected": integer,\n' \
' "state_code": string,\n' \
' "primary_party": string,\n' \
' "district_name": string,\n' \
'}'
template_values = {
'api_name': 'officeRetrieve',
'api_slug': 'officeRetrieve',
'api_introduction':
"Retrieve detailed information about one office.",
'try_now_link': 'apis_v1:officeRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/office_retrieve_doc.py",
"copies": "1",
"size": "3825",
"license": "bsd-3-clause",
"hash": 853299510410590500,
"line_mean": 41.5,
"line_max": 115,
"alpha_frac": 0.5035294118,
"autogenerated": false,
"ratio": 3.9030612244897958,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9901519001499863,
"avg_score": 0.0010143269579864916,
"num_lines": 90
} |
# apis_v1/documentation_source/offices_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def offices_sync_out_doc_template_values(url_root):
"""
Show documentation about officesSyncOut
"""
optional_query_parameter_list = [
{
'name': 'google_civic_election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the candidates retrieved to those for this google_civic_election_id.',
},
{
'name': 'state_code',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the offices entries retrieved to those in a particular state.',
},
]
potential_status_codes_list = [
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
'format': 'json',
}
api_response = '[{\n' \
' "we_vote_id": string,\n' \
' "office_name": string,\n' \
' "ballotpedia_id": string,\n' \
' "contest_level0": string,\n' \
' "contest_level1": string,\n' \
' "contest_level2": string,\n' \
' "district_id": string,\n' \
' "district_name": string,\n' \
' "district_scope": string,\n' \
' "electorate_specifications": string,\n' \
' "google_civic_office_name": string,\n' \
' "google_civic_office_name2": string,\n' \
' "google_civic_office_name3": string,\n' \
' "google_civic_office_name4": string,\n' \
' "google_civic_office_name5": string,\n' \
' "google_civic_election_id": integer,\n' \
' "maplight_id": integer,\n' \
' "ballotpedia_office_id": integer,\n' \
' "ballotpedia_office_name": string,\n' \
' "ballotpedia_office_url": string,\n' \
' "ballotpedia_race_id": integer,\n' \
' "ballotpedia_race_office_level": string,\n' \
' "number_elected": integer,\n' \
' "number_voting_for": integer,\n' \
' "ocd_division_id": integer,\n' \
' "primary_party": string,\n' \
' "special": string,\n' \
' "state_code": string,\n' \
' "wikipedia_id": string,\n' \
' "vote_usa_office_id": string,\n' \
'}]'
template_values = {
'api_name': 'officesSyncOut',
'api_slug': 'officesSyncOut',
'api_introduction':
"",
'try_now_link': 'apis_v1:officesSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/offices_sync_out_doc.py",
"copies": "1",
"size": "3303",
"license": "mit",
"hash": 684333088313877500,
"line_mean": 39.2804878049,
"line_max": 105,
"alpha_frac": 0.4647290342,
"autogenerated": false,
"ratio": 3.6098360655737705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9573373942922236,
"avg_score": 0.000238231370306842,
"num_lines": 82
} |
# apis_v1/documentation_source/organization_analytics_by_voter_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_analytics_by_voter_doc_template_values(url_root):
"""
Show documentation about organizationAnalyticsByVoter
"""
required_query_parameter_list = [
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'An organization\'s unique We Vote id.',
},
{
'name': 'organization_api_pass_code',
'value': 'string', # boolean, integer, long, string
'description': 'An organization\'s unique pass code for retrieving this data. '
'Not needed if organization is signed in.',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'Not needed if organization_api_pass_code is used.',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'election_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Limit the results to just this election',
},
{
'name': 'external_voter_id',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the results to just this voter',
},
{
'name': 'voter_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'Limit the results to just this voter',
},
]
potential_status_codes_list = [
# {
# 'code': 'VALID_VOTER_DEVICE_ID_MISSING',
# 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
# },
# {
# 'code': 'VALID_VOTER_ID_MISSING',
# 'description': 'Cannot proceed. A valid voter_id was not found.',
# },
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "organization_we_vote_id": string,\n' \
' "election_list": list\n' \
' [\n' \
' "election_id": string,\n' \
' "election_name": string,\n' \
' "election_date": string,\n' \
' "election_state": string,\n' \
' ],\n' \
' "voter_list": list\n' \
' [\n' \
' "external_voter_id": string (Unique ID from organization),\n' \
' "voter_we_vote_id": string (the voter\'s we vote id),\n' \
' "elections_visited: list,\n' \
' [\n' \
' "election_id": string (the election if within we vote),\n' \
' "support_count": integer (COMING SOON),\n' \
' "oppose_count: integer (COMING SOON),\n' \
' "friends_only_support_count": integer (COMING SOON),\n' \
' "friends_only_oppose_count: integer (COMING SOON),\n' \
' "friends_only_comments_count": integer (COMING SOON),\n' \
' "public_support_count": integer (COMING SOON),\n' \
' "public_oppose_count: integer (COMING SOON),\n' \
' "public_comments_count": integer (COMING SOON),\n' \
' ],\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'organizationAnalyticsByVoter',
'api_slug': 'organizationAnalyticsByVoter',
'api_introduction':
"A list of voter-specific analytics about either a) one of your member's, or b) all of your members "
"based on the variables you send with the request. These analytics come from visits to organization's "
"custom URL, and not the main WeVote.US site.",
'try_now_link': 'apis_v1:organizationAnalyticsByVoterView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_analytics_by_voter_doc.py",
"copies": "1",
"size": "5087",
"license": "mit",
"hash": 7759375510974800000,
"line_mean": 44.017699115,
"line_max": 115,
"alpha_frac": 0.4890898368,
"autogenerated": false,
"ratio": 3.9618380062305296,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.495092784303053,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_count_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_count_doc_template_values(url_root):
"""
Show documentation about organizationCount
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
# {
# 'name': '',
# 'value': '', # string, long, boolean
# 'description': '',
# },
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # string, long, boolean
# 'description': '',
# },
]
potential_status_codes_list = [
# {
# 'code': '',
# 'description': '',
# },
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "organization_count": integer,\n' \
' "success": boolean,\n' \
'}'
template_values = {
'api_name': 'organizationCount',
'api_slug': 'organizationCount',
'api_introduction':
"Return the number of endorsers in the database.",
'try_now_link': 'apis_v1:organizationCountView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_count_doc.py",
"copies": "1",
"size": "2005",
"license": "mit",
"hash": 7428716046626947000,
"line_mean": 31.3387096774,
"line_max": 115,
"alpha_frac": 0.5067331671,
"autogenerated": false,
"ratio": 3.8483685220729367,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9853623509534288,
"avg_score": 0.00029563592772984004,
"num_lines": 62
} |
# apis_v1/documentation_source/organization_daily_metrics_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_daily_metrics_sync_out_doc_template_values(url_root):
"""
Show documentation about organizationDailyMetricsSyncOut
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server. '
'If not provided, a new voter_device_id (and voter entry) '
'will be generated, and the voter_device_id will be returned.',
},
]
optional_query_parameter_list = [
{
'name': 'starting_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'The earliest date for the batch we are retrieving. Format: YYYYMMDD (ex/ 20200131) '
'(Default is 3 months ago)',
},
{
'name': 'ending_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'Retrieve data through this date. Format: YYYYMMDD (ex/ 20200228) (Default is right now.)'
},
{
'name': 'return_csv_format',
'value': 'boolean', # boolean, integer, long, string
'description': 'If set to true, return results in CSV format instead of JSON.'
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "id": integer,\n' \
' "authenticated_visitors_today": integer,\n' \
' "authenticated_visitors_total": integer,\n' \
' "auto_followers_total": integer,\n' \
' "date_as_integer": integer,\n' \
' "entrants_visiting_ballot": integer,\n' \
' "followers_total": integer,\n' \
' "followers_visiting_ballot": integer,\n' \
' "issues_linked_total": integer,\n' \
' "new_auto_followers_today": integer,\n' \
' "new_followers_today": integer,\n' \
' "new_visitors_today": integer,\n' \
' "organization_public_positions": integer,\n' \
' "organization_we_vote_id": integer,\n' \
' "visitors_today": integer,\n' \
' "visitors_total": integer,\n' \
' "voter_guide_entrants": integer,\n' \
' "voter_guide_entrants_today": integer,\n' \
'}]'
template_values = {
'api_name': 'organizationDailyMetricsSyncOut',
'api_slug': 'organizationDailyMetricsSyncOut',
'api_introduction':
"Allow people with Analytics Admin authority to retrieve organization daily metrics information "
"for data analysis purposes.",
'try_now_link': 'apis_v1:organizationDailyMetricsSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_daily_metrics_sync_out_doc.py",
"copies": "1",
"size": "3949",
"license": "mit",
"hash": -4626585866079073000,
"line_mean": 44.3908045977,
"line_max": 118,
"alpha_frac": 0.5330463408,
"autogenerated": false,
"ratio": 3.992922143579373,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5025968484379373,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_election_metrics_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_election_metrics_sync_out_doc_template_values(url_root):
"""
Show documentation about organizationElectionMetricsSyncOut
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server. '
'If not provided, a new voter_device_id (and voter entry) '
'will be generated, and the voter_device_id will be returned.',
},
]
optional_query_parameter_list = [
{
'name': 'starting_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'The earliest date for the batch we are retrieving. Format: YYYYMMDD (ex/ 20200131) '
'(Default is 3 months ago)',
},
{
'name': 'ending_date_as_integer',
'value': 'integer', # boolean, integer, long, string
'description': 'Retrieve data through this date. Format: YYYYMMDD (ex/ 20200228) (Default is right now.)'
},
{
'name': 'return_csv_format',
'value': 'boolean', # boolean, integer, long, string
'description': 'If set to true, return results in CSV format instead of JSON.'
},
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "id": integer,\n' \
' "authenticated_visitors_total": integer,\n' \
' "election_day_text": string,\n' \
' "entrants_friends_only_positions": integer,\n' \
' "entrants_friends_only_positions_with_comments": integer,\n' \
' "entrants_public_positions": integer,\n' \
' "entrants_public_positions_with_comments": integer,\n' \
' "entrants_took_position": integer,\n' \
' "entrants_visited_ballot": integer,\n' \
' "followers_at_time_of_election": integer,\n' \
' "followers_friends_only_positions": integer,\n' \
' "followers_friends_only_positions_with_comments": integer,\n' \
' "followers_public_positions": integer,\n' \
' "followers_public_positions_with_comments": integer,\n' \
' "followers_took_position": integer,\n' \
' "followers_visited_ballot": integer,\n' \
' "google_civic_election_id": integer,\n' \
' "new_auto_followers": integer,\n' \
' "new_followers": integer,\n' \
' "organization_we_vote_id": integer,\n' \
' "visitors_total": integer,\n' \
' "voter_guide_entrants": integer,\n' \
'}]'
template_values = {
'api_name': 'organizationElectionMetricsSyncOut',
'api_slug': 'organizationElectionMetricsSyncOut',
'api_introduction':
"Allow people with Analytics Admin authority to retrieve election metrics for one organization information "
"for data analysis purposes.",
'try_now_link': 'apis_v1:organizationElectionMetricsSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_election_metrics_sync_out_doc.py",
"copies": "1",
"size": "4338",
"license": "mit",
"hash": 6179106826238518000,
"line_mean": 46.6703296703,
"line_max": 120,
"alpha_frac": 0.5398801291,
"autogenerated": false,
"ratio": 4.020389249304912,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0012102198687111419,
"num_lines": 91
} |
# apis_v1/documentation_source/organization_follow_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_follow_doc_template_values(url_root):
"""
Show documentation about organizationFollow
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'organization_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Internal database unique identifier for organization',
},
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this organization across all networks '
'(either organization_id OR organization_we_vote_id required -- not both.) '
'NOTE: In the future we '
'might support other identifiers used in the industry.',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'A valid voter_id was not found from voter_device_id. Cannot proceed.',
},
{
'code': 'VALID_ORGANIZATION_ID_MISSING',
'description': 'A valid organization_id was not found. Cannot proceed.',
},
{
'code': 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING',
'description': 'An organization with that organization_id was not found. Cannot proceed.',
},
{
'code': 'FOLLOWING',
'description': 'Successfully following this organization',
},
]
try_now_link_variables_dict = {
'organization_id': '1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "organization_id": integer,\n' \
' "organization_we_vote_id": string,\n' \
'}'
template_values = {
'api_name': 'organizationFollow',
'api_slug': 'organizationFollow',
'api_introduction':
"Call this to save that the voter is following this organization.",
'try_now_link': 'apis_v1:organizationFollowView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/organization_follow_doc.py",
"copies": "1",
"size": "3606",
"license": "bsd-3-clause",
"hash": 5585276765637375000,
"line_mean": 39.5168539326,
"line_max": 115,
"alpha_frac": 0.5343871326,
"autogenerated": false,
"ratio": 4.212616822429907,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5247003955029907,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_follow_ignore_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_follow_ignore_doc_template_values(url_root):
"""
Show documentation about organizationFollowIgnore
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'organization_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Internal database unique identifier for organization',
},
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this organization across all networks '
'(either organization_id OR organization_we_vote_id required -- not both.) '
'NOTE: In the future we '
'might support other identifiers used in the industry.',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'A valid voter_device_id parameter was not included. Cannot proceed.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'A valid voter_id was not found from voter_device_id. Cannot proceed.',
},
{
'code': 'VALID_ORGANIZATION_ID_MISSING',
'description': 'A valid organization_id was not found. Cannot proceed.',
},
{
'code': 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE',
'description': 'An organization with that organization_id was not found. Cannot proceed.',
},
{
'code': 'FOLLOW_IGNORE',
'description': 'Successfully ignoring this organization',
},
]
try_now_link_variables_dict = {
'organization_id': '1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "organization_id": integer,\n' \
' "organization_we_vote_id": string,\n' \
'}'
template_values = {
'api_name': 'organizationFollowIgnore',
'api_slug': 'organizationFollowIgnore',
'api_introduction':
"Call this to save that the voter is ignoring this organization.",
'try_now_link': 'apis_v1:organizationFollowIgnoreView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/documentation_source/organization_follow_ignore_doc.py",
"copies": "3",
"size": "3650",
"license": "mit",
"hash": -4766013468534955000,
"line_mean": 40.0112359551,
"line_max": 115,
"alpha_frac": 0.5389041096,
"autogenerated": false,
"ratio": 4.214780600461894,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6253684710061894,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_index_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_index_doc_template_values(url_root):
"""
Show documentation about organizationIndex
"""
required_query_parameter_list = [
]
optional_query_parameter_list = [
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = 'The raw HTML for index.html is returned, using the endorser\'s custom settings'
template_values = {
'api_name': 'organizationIndex',
'api_slug': 'organizationIndex',
'api_introduction':
"Return a customized index.html (as text). Add /ORGANIZATION_URL after organizationIndex in the URL. "
"Ex/ https://api.wevoteusa.org/apis/v1/organizationIndex/www.domain.org",
'try_now_link': 'apis_v1:organizationIndexView',
'try_now_link_additional_path': 'www.domain.org',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_index_doc.py",
"copies": "1",
"size": "1421",
"license": "mit",
"hash": -5332946353843226000,
"line_mean": 33.6585365854,
"line_max": 114,
"alpha_frac": 0.6389866291,
"autogenerated": false,
"ratio": 3.5883838383838382,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9723672472465466,
"avg_score": 0.0007395990036745666,
"num_lines": 41
} |
# apis_v1/documentation_source/organization_link_to_issue_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_link_to_issue_sync_out_doc_template_values(url_root):
"""
Show documentation about organizationLinkToIssueSyncOut
"""
optional_query_parameter_list = [
]
potential_status_codes_list = [
]
try_now_link_variables_dict = {
}
api_response = '[{\n' \
' "issue_we_vote_id": string,\n' \
' "organization_we_vote_id": string,\n' \
' "link_active": boolean,\n' \
' "reason_for_link": string,\n' \
' "link_blocked": boolean,\n' \
' "reason_link_is_blocked": string,\n' \
'}]'
template_values = {
'api_name': 'organizationLinkToIssueSyncOut',
'api_slug': 'organizationLinkToIssueSyncOut',
'api_introduction':
"This is the summary of the way that public endorsers are categorized by issues. "
"For example, if I want to find all endorsers that are related to climate change, "
"this is the data that tells me this.",
'try_now_link': 'apis_v1:organizationLinkToIssueSyncOutView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_link_to_issue_sync_out_doc.py",
"copies": "1",
"size": "1662",
"license": "mit",
"hash": -3765318291489627600,
"line_mean": 35.9333333333,
"line_max": 95,
"alpha_frac": 0.5776173285,
"autogenerated": false,
"ratio": 3.62882096069869,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9704111291148008,
"avg_score": 0.00046539961013645223,
"num_lines": 45
} |
# apis_v1/documentation_source/organization_photos_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_photos_save_doc_template_values(url_root):
"""
Show documentation about organizationPhotosSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'organization_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The internal database id for this organization. '
'(One of these is required to update data: '
'organization_id, organization_we_vote_id or organization_twitter_handle)',
},
{
'name': 'organization_twitter_handle',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this organization across all networks. '
'(One of these is required to update data: '
'organization_id, organization_we_vote_id, organization_twitter_handle)',
},
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this organization across all networks. '
'(One of these is required to update data: '
'organization_id, organization_we_vote_id, organization_twitter_handle)',
},
]
optional_query_parameter_list = [
{
'name': 'chosen_favicon_from_file_reader',
'value': 'string', # boolean, integer, long, string
'description': 'This is the output from JavaScript\'s FileReader for an uploaded favicon image.',
},
{
'name': 'chosen_logo_from_file_reader',
'value': 'string', # boolean, integer, long, string
'description': 'This is the output from JavaScript\'s FileReader for an uploaded logo.',
},
{
'name': 'chosen_social_share_master_image_from_file_reader',
'value': 'string', # boolean, integer, long, string
'description': 'This is the output from JavaScript\'s FileReader for an uploaded social share image.',
},
{
'name': 'delete_chosen_favicon',
'value': 'boolean', # boolean, integer, long, string
'description': 'Tell the API server to delete the current favicon for this organization.',
},
{
'name': 'delete_chosen_logo',
'value': 'boolean', # boolean, integer, long, string
'description': 'Tell the API server to delete the current logo for this organization.',
},
{
'name': 'delete_chosen_social_share_master_image',
'value': 'boolean', # boolean, integer, long, string
'description': 'Tell the API server to delete the current social share master image '
'for this organization.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "organization_id": integer,\n' \
' "organization_we_vote_id": string,\n' \
'}'
template_values = {
'api_name': 'organizationPhotosSave',
'api_slug': 'organizationPhotosSave',
'api_introduction':
"Save uploaded photos for an existing organization.",
'try_now_link': 'apis_v1:organizationPhotosSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'POST',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_photos_save_doc.py",
"copies": "1",
"size": "5192",
"license": "mit",
"hash": -4892094290590171000,
"line_mean": 44.147826087,
"line_max": 115,
"alpha_frac": 0.5337057011,
"autogenerated": false,
"ratio": 4.337510442773601,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5371216143873601,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_retrieve_doc_template_values(url_root):
"""
Show documentation about organizationRetrieve
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'organization_id',
'value': 'integer', # boolean, integer, long, string
'description': 'Internal database unique identifier (one identifier required, '
'either organization_id or organization_we_vote_id)',
},
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'We Vote unique identifier so we can move endorsers from server-to-server '
'(one identifier required, either id or we_vote_id)',
},
]
optional_query_parameter_list = [
# {
# 'name': '',
# 'value': '', # boolean, integer, long, string
# 'description': '',
# },
]
potential_status_codes_list = [
{
'code': 'ORGANIZATION_FOUND_WITH_ID',
'description': 'The organization was found using the internal id',
},
{
'code': 'ORGANIZATION_FOUND_WITH_WE_VOTE_ID',
'description': 'The organization was found using the we_vote_id',
},
{
'code': 'ORGANIZATION_RETRIEVE_BOTH_IDS_MISSING',
'description': 'One identifier required. Neither provided.',
},
{
'code': 'ORGANIZATION_NOT_FOUND_WITH_ID',
'description': 'The organization was not found with internal id.',
},
{
'code': 'ERROR_<specifics here>',
'description': 'An internal description of what error prevented the retrieve of the organization.',
},
]
try_now_link_variables_dict = {
'organization_we_vote_id': 'wv85org1',
}
# Changes made here should also be made in organizations_followed_retrieved
api_response = '{\n' \
' "success": boolean,\n' \
' "status": string,\n' \
' "facebook_id": integer,\n' \
' "organization_banner_url": string,\n' \
' "organization_description": string,\n' \
' "organization_email": string,\n' \
' "organization_facebook": string,\n' \
' "organization_id": integer (the id of the organization found),\n' \
' "organization_instagram_handle": string,\n' \
' "organization_name": string (value from Google),\n' \
' "organization_photo_url_large": string,\n' \
' "organization_photo_url_medium": string,\n' \
' "organization_photo_url_tiny": string,\n' \
' "organization_type": string,\n' \
' "organization_twitter_handle": string (twitter address),\n' \
' "organization_we_vote_id": string (the organization identifier that moves server-to-server),\n' \
' "organization_website": string (website address),\n' \
' "twitter_description": string,\n' \
' "twitter_followers_count": integer,\n' \
'}'
template_values = {
'api_name': 'organizationRetrieve',
'api_slug': 'organizationRetrieve',
'api_introduction':
"Retrieve the organization using organization_id (first choice) or we_vote_id.",
'try_now_link': 'apis_v1:organizationRetrieveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/documentation_source/organization_retrieve_doc.py",
"copies": "1",
"size": "4558",
"license": "mit",
"hash": -1014443539363234700,
"line_mean": 43.6862745098,
"line_max": 119,
"alpha_frac": 0.5276437034,
"autogenerated": false,
"ratio": 4.189338235294118,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5216981938694117,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_save_doc_template_values(url_root):
"""
Show documentation about organizationSave
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'organization_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The internal database id for this organization. '
'(One of these is required: '
'organization_id, organization_we_vote_id, '
'organization_website or organization_twitter_handle)',
},
{
'name': 'organization_we_vote_id',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this organization across all networks. '
'(One of these is required: '
'organization_id, organization_we_vote_id, '
'organization_website or organization_twitter_handle)',
},
]
optional_query_parameter_list = [
{
'name': 'organization_name',
'value': 'string', # boolean, integer, long, string
'description': 'Name of the organization that is displayed.',
},
{
'name': 'organization_email',
'value': 'string', # boolean, integer, long, string
'description': 'Contact email of the organization.',
},
{
'name': 'organization_website',
'value': 'string', # boolean, integer, long, string
'description': 'Website of the organization.',
},
{
'name': 'organization_twitter_handle',
'value': 'string', # boolean, integer, long, string
'description': 'Twitter handle of the organization.',
},
{
'name': 'organization_facebook',
'value': 'string', # boolean, integer, long, string
'description': 'Facebook page of the organization.',
},
{
'name': 'organization_image',
'value': 'string', # boolean, integer, long, string
'description': 'Logo of the organization that is displayed.',
},
{
'name': 'refresh_from_twitter',
'value': 'boolean', # boolean, integer, long, string
'description': 'Augment the data passed in with information from Twitter. Do not replace data passed in '
'as a variable with the data from Twitter, but if a variable is not passed in via the API, '
'then fill in that variable with data from Twitter. One use-case is to save an '
'organization with only a Twitter handle, and fill in the rest of the data with a call '
'to Twitter.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
{
'code': 'ORGANIZATION_REQUIRED_UNIQUE_IDENTIFIER_VARIABLES_MISSING',
'description': 'Cannot proceed. Missing sufficient unique identifiers for either save new or update.',
},
{
'code': 'NEW_ORGANIZATION_REQUIRED_VARIABLES_MISSING',
'description': 'Cannot proceed. This is a new entry and there are not sufficient variables.',
},
{
'code': 'FOUND_WITH_WEBSITE SAVED',
'description': 'An organization with matching website was found. Record updated.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "organization_id": integer,\n' \
' "organization_we_vote_id": string,\n' \
' "new_organization_created": boolean,\n' \
' "organization_name": string,\n' \
' "organization_email": string,\n' \
' "organization_website": string,\n' \
' "organization_facebook": string,\n' \
' "organization_photo_url": string,\n' \
' "organization_twitter_handle": string,\n' \
' "twitter_followers_count": integer,\n' \
' "twitter_description": string,\n' \
' "refresh_from_twitter": boolean,\n' \
'}'
template_values = {
'api_name': 'organizationSave',
'api_slug': 'organizationSave',
'api_introduction':
"Save a new organization or update an existing organization. Note that passing in a blank value does not "
"delete an existing value. We may want to come up with a variable we pass if we want to clear a value.",
'try_now_link': 'apis_v1:organizationSaveView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/organization_save_doc.py",
"copies": "1",
"size": "6493",
"license": "bsd-3-clause",
"hash": 4874754180948963000,
"line_mean": 45.0496453901,
"line_max": 120,
"alpha_frac": 0.5173263515,
"autogenerated": false,
"ratio": 4.474844934527912,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5492171286027911,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/organization_search_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def organization_search_doc_template_values(url_root):
"""
Show documentation about organizationSearch
"""
required_query_parameter_list = [
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
]
optional_query_parameter_list = [
{
'name': 'organization_name',
'value': 'string', # boolean, integer, long, string
'description': 'Name of the organization that is displayed.',
},
{
'name': 'organization_email',
'value': 'string', # boolean, integer, long, string
'description': 'Contact email of the organization.',
},
{
'name': 'organization_website',
'value': 'string', # boolean, integer, long, string
'description': 'Website of the organization.',
},
{
'name': 'organization_twitter_handle',
'value': 'string', # boolean, integer, long, string
'description': 'Twitter handle of the organization.',
},
]
potential_status_codes_list = [
{
'code': 'VALID_VOTER_DEVICE_ID_MISSING',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': 'VALID_VOTER_ID_MISSING',
'description': 'Cannot proceed. A valid voter_id was not found.',
},
{
'code': 'ORGANIZATION_SEARCH_ALL_TERMS_MISSING',
'description': 'Cannot proceed. No search terms were provided.',
},
{
'code': 'ORGANIZATIONS_RETRIEVED',
'description': 'Successfully returned a list of organizations that match search query.',
},
{
'code': 'NO_ORGANIZATIONS_RETRIEVED',
'description': 'Successfully searched, but no organizations found that match search query.',
},
]
try_now_link_variables_dict = {
# 'organization_we_vote_id': 'wv85org1',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "organization_email": string (the original search term passed in),\n' \
' "organization_name": string (the original search term passed in),\n' \
' "organization_twitter_handle": string (the original search term passed in),\n' \
' "organization_website": string (the original search term passed in),\n' \
' "organizations_list": list\n' \
' [\n' \
' "organization_id": integer,\n' \
' "organization_we_vote_id": string,\n' \
' "organization_name": string,\n' \
' "organization_twitter_handle": string,\n' \
' "organization_facebook": string,\n' \
' "organization_email": string,\n' \
' "organization_website": string,\n' \
' ],\n' \
'}'
template_values = {
'api_name': 'organizationSearch',
'api_slug': 'organizationSearch',
'api_introduction':
"Find a list of all organizations that match any of the search terms.",
'try_now_link': 'apis_v1:organizationSearchView',
'try_now_link_variables_dict': try_now_link_variables_dict,
'url_root': url_root,
'get_or_post': 'GET',
'required_query_parameter_list': required_query_parameter_list,
'optional_query_parameter_list': optional_query_parameter_list,
'api_response': api_response,
'api_response_notes':
"",
'potential_status_codes_list': potential_status_codes_list,
}
return template_values
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/documentation_source/organization_search_doc.py",
"copies": "1",
"size": "4594",
"license": "bsd-3-clause",
"hash": -1202418183420387800,
"line_mean": 41.537037037,
"line_max": 115,
"alpha_frac": 0.5156726165,
"autogenerated": false,
"ratio": 4.2380073800738005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.52536799965738,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.