text stringlengths 0 1.05M | meta dict |
|---|---|
# apis_v1/documentation_source/voter_star_status_retrieve_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_star_status_retrieve_doc_template_values(url_root):
"""
Show documentation about voterStarStatusRetrieve
"""
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_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'What is the type of ballot item for which we are retrieving the status? '
'(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_id': '5655',
}
api_response = '{\n' \
' "status": string,\n' \
' "success": boolean,\n' \
' "voter_device_id": string (88 characters long),\n' \
' "is_starred": boolean,\n' \
' "office_id": integer,\n' \
' "candidate_id": integer,\n' \
' "measure_id": integer,\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStarStatusRetrieve',
'api_slug': 'voterStarStatusRetrieve',
'api_introduction':
"Is the star next to this office, candidate, or measure starred for this voter?",
'try_now_link': 'apis_v1:voterStarStatusRetrieveView',
'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/voter_star_status_retrieve_doc.py",
"copies": "1",
"size": "3982",
"license": "bsd-3-clause",
"hash": 5254674576067759000,
"line_mean": 43.2444444444,
"line_max": 115,
"alpha_frac": 0.5266197891,
"autogenerated": false,
"ratio": 3.836223506743738,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4862843295843738,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/voter_stop_opposing_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_stop_opposing_save_doc_template_values(url_root):
"""
Show documentation about voterStopOpposingSave
"""
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': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'The kind of ballot item the voter wants to stop opposing. '
'(kind_of_ballot_item is either "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier of the ballot item the voter wants to stop opposing. '
'(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. Missing voter_id while trying to save.',
},
{
'code': 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING',
'description': 'Cannot proceed. Neither candidate_id nor measure_id were included.',
},
{
'code': 'STOP_OPPOSING_CANDIDATE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'STOP_OPPOSING_CANDIDATE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'STOP_OPPOSING_CANDIDATE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'STOP_OPPOSING_CANDIDATE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
{
'code': 'STOP_OPPOSING_MEASURE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'STOP_OPPOSING_MEASURE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'STOP_OPPOSING_MEASURE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'STOP_OPPOSING_MEASURE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStopOpposingSave',
'api_slug': 'voterStopOpposingSave',
'api_introduction':
"Save or update an entry for the current voter for either a measure or candidate, "
"so voter no longer opposing. This does not mean that they support.",
'try_now_link': 'apis_v1:voterStopOpposingSaveView',
'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/voter_stop_opposing_save_doc.py",
"copies": "3",
"size": "5400",
"license": "bsd-3-clause",
"hash": 3577176962938382300,
"line_mean": 43.262295082,
"line_max": 115,
"alpha_frac": 0.5355555556,
"autogenerated": false,
"ratio": 3.8162544169611308,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002013530185181896,
"num_lines": 122
} |
# apis_v1/documentation_source/voter_stop_supporting_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_stop_supporting_save_doc_template_values(url_root):
"""
Show documentation about voterStopSupportingSave
"""
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': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'The kind of ballot item the voter wants to stop supporting. '
'(kind_of_ballot_item is either "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier of the ballot item the voter wants to stop supporting. '
'(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. Missing voter_id while trying to save.',
},
{
'code': 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING',
'description': 'Cannot proceed. Neither candidate_id nor measure_id were included.',
},
{
'code': 'STOP_SUPPORTING_CANDIDATE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'STOP_SUPPORTING_CANDIDATE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'STOP_SUPPORTING_CANDIDATE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'STOP_SUPPORTING_CANDIDATE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
{
'code': 'STOP_SUPPORTING_MEASURE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'STOP_SUPPORTING_MEASURE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'STOP_SUPPORTING_MEASURE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'STOP_SUPPORTING_MEASURE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStopSupportingSave',
'api_slug': 'voterStopSupportingSave',
'api_introduction':
"Save or update an entry for the current voter for either a measure or candidate, "
"so voter no longer supports. This does not mean that they oppose.",
'try_now_link': 'apis_v1:voterStopSupportingSaveView',
'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/voter_stop_supporting_save_doc.py",
"copies": "3",
"size": "5431",
"license": "mit",
"hash": -7728557728156666000,
"line_mean": 43.5163934426,
"line_max": 116,
"alpha_frac": 0.5382065918,
"autogenerated": false,
"ratio": 3.890401146131805,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5928607737931805,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/voter_supporting_save_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_supporting_save_doc_template_values(url_root):
"""
Show documentation about voterSupportingSave
"""
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': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'The kind of ballot item the voter is supporting. '
'(kind_of_ballot_item is either "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier of the ballot item the voter is supporting. '
'(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. Missing voter_id while trying to save.',
},
{
'code': 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING',
'description': 'Cannot proceed. Neither candidate_id nor measure_id were included.',
},
{
'code': 'SUPPORTING_CANDIDATE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'SUPPORTING_CANDIDATE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'SUPPORTING_CANDIDATE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'SUPPORTING_CANDIDATE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
{
'code': 'SUPPORTING_MEASURE STANCE_UPDATED',
'description': 'Success. Existing entry updated.',
},
{
'code': 'SUPPORTING_MEASURE NEW_STANCE_SAVED',
'description': 'Success. New entry created.',
},
{
'code': 'SUPPORTING_MEASURE STANCE_COULD_NOT_BE_UPDATED',
'description': 'Cannot proceed. Existing entry could not be updated.',
},
{
'code': 'SUPPORTING_MEASURE NEW_STANCE_COULD_NOT_BE_SAVED',
'description': 'Cannot proceed. New entry could not be created.',
},
]
try_now_link_variables_dict = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "ballot_item_we_vote_id": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterSupportingSave',
'api_slug': 'voterSupportingSave',
'api_introduction':
"Save or create support stance for the current voter for either a measure or candidate.",
'try_now_link': 'apis_v1:voterSupportingSaveView',
'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/voter_supporting_save_doc.py",
"copies": "3",
"size": "5268",
"license": "mit",
"hash": -609635633713504400,
"line_mean": 42.5371900826,
"line_max": 115,
"alpha_frac": 0.532080486,
"autogenerated": false,
"ratio": 3.902222222222222,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5934302708222221,
"avg_score": null,
"num_lines": null
} |
# apis_v1/documentation_source/voter_twitter_save_to_current_account_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_twitter_save_to_current_account_doc_template_values(url_root):
"""
Show documentation about voterTwitterSaveToCurrentAccount
"""
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': 'twitter_secret_key',
'value': 'string', # boolean, integer, long, string
'description': 'The secret key we use to find the record in the twitter_auth_response table.',
},
]
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': 'voterTwitterSaveToCurrentAccount',
'api_slug': 'voterTwitterSaveToCurrentAccount',
'api_introduction':
"",
'try_now_link': 'apis_v1:voterTwitterSaveToCurrentAccountView',
'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/voter_twitter_save_to_current_account_doc.py",
"copies": "2",
"size": "2551",
"license": "mit",
"hash": 899691113006147000,
"line_mean": 37.0746268657,
"line_max": 115,
"alpha_frac": 0.5558604469,
"autogenerated": false,
"ratio": 3.847662141779789,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007060459924612547,
"num_lines": 67
} |
# apis_v1/documentation_source/voter_update_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_update_doc_template_values(url_root):
"""
Show documentation about voterUpdate
"""
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',
},
]
optional_query_parameter_list = [
{
'name': 'facebook_email',
'value': 'string', # boolean, integer, long, string
'description': 'The voter\'s email from facebook.',
},
{
'name': 'facebook_profile_image_url_https',
'value': 'string', # boolean, integer, long, string
'description': 'The url on the facebook servers of this person\'s profile photo.',
},
{
'name': 'first_name',
'value': 'string', # boolean, integer, long, string
'description': 'The first name to update to.',
},
{
'name': 'first_name_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the voter\'s first name?',
},
{
'name': 'middle_name',
'value': 'string', # boolean, integer, long, string
'description': 'The middle name to update to.',
},
{
'name': 'last_name',
'value': 'string', # boolean, integer, long, string
'description': 'The last name (family name) to update to.',
},
{
'name': 'last_name_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the voter\'s last name?',
},
{
'name': 'twitter_profile_image_url_https',
'value': 'string', # boolean, integer, long, string
'description': 'The url on the twitter servers of this person\'s profile photo.',
},
{
'name': 'interface_status_flags',
'value': 'integer', # boolean, integer, long, string
'description': 'An integer whose bits represent several flags for the user, such as the ',
},
{
'name': 'flag_integer_to_set',
'value': 'integer', # boolean, integer, long, string
'description': 'Sets the corresponding bit represented by this integer\'s bit, '
'in interface_status_flags bit',
},
{
'name': 'flag_integer_to_unset',
'value': 'integer', # boolean, integer, long, string
'description': 'Unsets the corresponding bit represented by this integer\'s bit, '
'in interface_status_flags bit',
},
{
'name': 'notification_settings_flags',
'value': 'integer', # boolean, integer, long, string
'description': 'An integer whose bits represent several flags for the user, such as the ',
},
{
'name': 'notification_flag_integer_to_set',
'value': 'integer', # boolean, integer, long, string
'description': 'Sets the corresponding bit represented by this integer\'s bit, '
'in notification_settings_flags bit',
},
{
'name': 'notification_flag_integer_to_unset',
'value': 'integer', # boolean, integer, long, string
'description': 'Unsets the corresponding bit represented by this integer\'s bit, '
'in notification_settings_flags bit',
},
{
'name': 'voter_photo_from_file_reader',
'value': 'string', # boolean, integer, long, string
'description': 'The binary photo uploaded by voter.',
},
{
'name': 'voter_photo_changed',
'value': 'boolean', # boolean, integer, long, string
'description': 'Are we trying to change the voter\'s uploaded photo?',
},
]
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',
'description': 'Cannot proceed. Missing variables voter_id while trying to save.',
},
{
'code': 'UPDATED_VOTER',
'description': 'Successfully saved',
},
]
try_now_link_variables_dict = {
'facebook_email': 'False',
'facebook_profile_image_url_https': 'False',
'first_name': 'False',
'middle_name': 'False',
'last_name': 'False',
'twitter_profile_image_url_https': 'False',
'interface_status_flags': 'False',
'flag_integer_to_set': 'False',
'flag_integer_to_unset': 'False',
'notification_settings_flags': 'False',
'notification_flag_integer_to_set': 'False',
'notification_flag_integer_to_unset': 'False',
}
# TODO: update api_response with all the variables, such as first_name and last_name
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (True as long as no db errors),\n' \
' "voter_device_id": string (88 characters long),\n' \
' "voter_updated": boolean (did the voter address save happen?),\n' \
' "facebook_profile_image_url_https": string,\n' \
' "twitter_profile_image_url_https": 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' \
' "interface_status_flags": integer,\n' \
' "flag_integer_to_set": integer,\n' \
' "flag_integer_to_unset": integer,\n' \
' "notification_settings_flags": integer,\n' \
' "notification_flag_integer_to_set": integer,\n' \
' "notification_flag_integer_to_unset": integer,\n' \
'}'
template_values = {
'api_name': 'voterUpdate',
'api_slug': 'voterUpdate',
'api_introduction':
"Update profile-related information for the current voter. If the string 'False' is passed "
"(or the boolean value), do not update the field.",
'try_now_link': 'apis_v1:voterUpdateView',
'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/voter_update_doc.py",
"copies": "1",
"size": "7874",
"license": "mit",
"hash": -4015227381384591000,
"line_mean": 43.9942857143,
"line_max": 115,
"alpha_frac": 0.5102870206,
"autogenerated": false,
"ratio": 4.139852786540484,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000997267470074843,
"num_lines": 175
} |
# apis_v1/documentation_source/voter_verify_secret_code_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def voter_verify_secret_code_doc_template_values(url_root):
"""
Show documentation about voterVerifySecretCode
"""
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': 'secret_code',
'value': 'string', # boolean, integer, long, string
'description': 'The six digit code to verify.',
},
]
optional_query_parameter_list = [
{
'name': 'code_sent_to_sms_phone_number',
'value': 'boolean', # boolean, integer, long, string
'description': 'If true, process this verification for an SMS phone number. If false, process for email.',
},
]
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_DEVICE_ID-VOTER_RETRIEVE',
# 'description': 'There is no voter_id attached to that voter_device_id',
# },
# {
# 'code': 'VOTER_ID_COULD_NOT_BE_RETRIEVED',
# 'description': 'Unable to retrieve voter_id, although voter_id was found linked to voter_device_id',
# },
]
try_now_link_variables_dict = {
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (True as long as no db errors),\n' \
' "incorrect_secret_code_entered": boolean,\n' \
' "number_of_tries_remaining_for_this_code": integer,\n' \
' "secret_code_verified": boolean,\n' \
' "voter_must_request_new_code": boolean,\n' \
' "secret_code_system_locked_for_this_voter_device_id": string,\n' \
'}'
template_values = {
'api_name': 'voterVerifySecretCode',
'api_slug': 'voterVerifySecretCode',
'api_introduction': "Voter submits this six digit code to verify that they received an SMS message or email.",
'try_now_link': 'apis_v1:voterVerifySecretCodeView',
'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/voter_verify_secret_code_doc.py",
"copies": "1",
"size": "3288",
"license": "mit",
"hash": -3974457857774130700,
"line_mean": 41.7012987013,
"line_max": 119,
"alpha_frac": 0.5538321168,
"autogenerated": false,
"ratio": 3.732122587968218,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47859547047682177,
"avg_score": null,
"num_lines": null
} |
# apis_v1/tests/test_views_voter_sms_phone_number_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.urls import reverse
from django.test import TestCase
from email_outbound.models import EmailAddress, EmailManager
import json
class WeVoteAPIsV1TestsVoterSMSPhoneNumberRetrieve(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.voter_sms_phone_number_save_url = reverse("apis_v1:voterSMSPhoneNumberSaveView")
self.voter_sms_phone_number_retrieve_url = reverse("apis_v1:voterSMSPhoneNumberRetrieveView")
def test_retrieve_with_no_voter_device_id(self):
response = self.client.get(self.voter_sms_phone_number_retrieve_url)
json_data = json.loads(response.content.decode())
self.assertEqual('status' in json_data, True, "status expected in the json response, and not found")
self.assertEqual(json_data['status'],
"VALID_VOTER_DEVICE_ID_MISSING",
"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING"
"voter_device_id: {voter_device_id}".format(status=json_data['status'],
voter_device_id=json_data['voter_device_id']))
self.assertEqual(len(json_data['sms_phone_number_list']),
0,
"Expected sms_phone_number_list to have length 0, "
"actual_length = {length}".format(length=len(json_data["sms_phone_number_list"])))
def test_retrieve_with_voter_device_id(self):
response = self.client.get(self.generate_voter_device_id_url)
json_data = json.loads(response.content.decode())
voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else ''
# Create a voter so we can test retrieve
response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data2 = json.loads(response2.content.decode())
self.assertEqual('status' in json_data2, True,
"status expected in the voterSMSPhoneNumberRetrieve json response but not found")
self.assertEqual('voter_device_id' in json_data2, True,
"voter_device_id expected in the voterSMSPhoneNumberRetrieve json response but not found")
# Retrieve voter's phone number list (verify that voter does not have an phone number list)
response3 = self.client.get(self.voter_sms_phone_number_retrieve_url, {'voter_device_id':voter_device_id})
json_data3 = json.loads(response3.content.decode())
self.assertEqual('status' in json_data3, True,
"status expected in the json response, and not found")
self.assertEqual(json_data3['status'],
"NO_SMS_PHONE_NUMBER_LIST_RETRIEVED ",
"status = {status} Expected status NO_SMS_PHONE_NUMBER_LIST_RETRIEVED"
"voter_device_id: {voter_device_id}".format(status=json_data3['status'],
voter_device_id=json_data3['voter_device_id']))
self.assertEqual(len(json_data3['sms_phone_number_list']), 0,
"Expected sms_phone_number_list to have length 0, "
"actual length = {length}".format(length=len(json_data3['sms_phone_number_list'])))
# Valid Voter Device ID with a Phone Number
# Save a phone number for the voter
# Note: When saving a phone number, system checks to see if the area code is valid
self.client.get(self.voter_sms_phone_number_save_url, {'sms_phone_number':
'888-888-8888',
'voter_device_id': voter_device_id})
# Retrieve the voter's sms phone number
response5 = self.client.get(self.voter_sms_phone_number_retrieve_url, {'voter_device_id': voter_device_id})
json_data5 = json.loads(response5.content.decode())
# Verify that the response contains one sms phone number
self.assertEqual(len(json_data5['sms_phone_number_list']), 1,
'Expected sms_phone_number_list to have length 1, '
'actual length = {length}'.format(length=len(json_data5['sms_phone_number_list'])))
# Verify that the response's sms phone number is correct (matches the one we created)
response_number = json_data5["sms_phone_number_list"][0]["normalized_sms_phone_number"]
self.assertEqual(response_number, '+1 888-888-8888',
'Expected sms phone number to be 888-888-8888, '
'actual sms phone number = {sms_phone_number}'.format(sms_phone_number=response_number))
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_voter_sms_phone_number_retrieve.py",
"copies": "1",
"size": "5097",
"license": "mit",
"hash": 6415936813966341000,
"line_mean": 57.5862068966,
"line_max": 117,
"alpha_frac": 0.607612321,
"autogenerated": false,
"ratio": 3.849697885196375,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4957310206196375,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_campaign_list_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from admin_tools.controllers import import_data_for_tests
from django.urls import reverse
from django.test import TestCase
import json
from office.models import ContestOffice, ContestOfficeManager
class WeVoteAPIsV1TestsCampaignListRetrieve(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.campaign_list_retrieve_url = reverse("apis_v1:campaignListRetrieveView")
def test_retrieve_with_no_voter_device_id(self):
#######################################
# Without a cookie or required variables, we don't expect valid response
response = self.client.get(self.campaign_list_retrieve_url)
json_data = json.loads(response.content.decode())
# print(json_data)
self.assertEqual('status' in json_data, True,
"status expected in the json response, and not found")
self.assertEqual('success' in json_data, True,
"success expected in the json response, and not found")
self.assertEqual(len(json_data['campaignx_list']), 0,
"Expected campaignx_list to have length 0, "
"actual length = {length}".format(length=len(json_data['campaignx_list'])))
self.assertEqual(json_data['status'], 'VOTER_WE_VOTE_ID_COULD_NOT_BE_FETCHED ',
"status: {status} (VOTER_WE_VOTE_ID_COULD_NOT_BE_FETCHED expected), ".format(
status=json_data['status']))
self.assertEqual(json_data['success'], False, "success: {success} (success 'False' expected), ".format(
success=json_data['success']))
self.assertListEqual(json_data['campaignx_list'], [],
"campaignx_list: {campaignx_list} (Empty list expected), ".format(
campaignx_list=json_data['campaignx_list']))
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_campaign_list_retrieve.py",
"copies": "1",
"size": "2175",
"license": "mit",
"hash": -1180101732422628600,
"line_mean": 50.7857142857,
"line_max": 111,
"alpha_frac": 0.6395402299,
"autogenerated": false,
"ratio": 3.8427561837455833,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49822964136455833,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_candidates_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from admin_tools.controllers import import_data_for_tests
from django.urls import reverse
from django.test import TestCase
import json
from office.models import ContestOffice, ContestOfficeManager
class WeVoteAPIsV1TestsCandidatesRetrieve(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.candidates_retrieve_url = reverse("apis_v1:candidatesRetrieveView")
def test_retrieve_with_no_voter_device_id(self):
#######################################
# Without a cookie or required variables, we don't expect valid response
response01 = self.client.get(self.candidates_retrieve_url)
json_data01 = json.loads(response01.content.decode())
self.assertEqual('status' in json_data01, True, "status expected in the json response, and not found")
self.assertEqual('success' in json_data01, True, "success expected in the json response, and not found")
self.assertEqual('office_id' in json_data01, True, "office_id expected in the json response, and not found")
self.assertEqual('office_we_vote_id' in json_data01, True,
"office_we_vote_id expected in the json response, and not found")
self.assertEqual('google_civic_election_id' in json_data01, True,
"google_civic_election_id expected in the json response, and not found")
self.assertEqual('candidate_list' in json_data01, True,
"candidate_list expected in the json response, and not found")
self.assertEqual(
json_data01['status'], 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
"status: {status} (VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING expected), ".format(
status=json_data01['status']))
self.assertEqual(json_data01['success'], False, "success: {success} (success 'False' expected), ".format(
success=json_data01['success']))
self.assertEqual(json_data01['office_id'], 0, "office_id: {office_id} ('0' expected), ".format(
office_id=json_data01['office_id']))
self.assertEqual(json_data01['office_we_vote_id'], '',
"office_we_vote_id: {office_we_vote_id} ('' expected), ".format(
office_we_vote_id=json_data01['office_we_vote_id']))
self.assertEqual(json_data01['google_civic_election_id'], 0,
"google_civic_election_id: {google_civic_election_id} ('0' expected), ".format(
google_civic_election_id=json_data01['google_civic_election_id']))
self.assertListEqual(json_data01['candidate_list'], [],
"candidate_list: {candidate_list} (Empty list expected), ".format(
candidate_list=json_data01['candidate_list']))
# NOTE: There is a problem with the import_data. Test disabled.
# #######################################
# # We want to import some election-related data so we can test lists
# import_data_for_tests()
#
# #######################################
# # Retrieve contest_office so we can work with it
# contest_office_manager = ContestOfficeManager()
# results = contest_office_manager.retrieve_contest_office_from_we_vote_id(
# contest_office_we_vote_id='wv01off922')
#
# self.assertEqual('success' in results, True,
# "Unable to retrieve contest_office with contest_office_we_vote_id='wv01off922'")
#
# if results['success']:
# contest_office = results['contest_office']
# else:
# contest_office = ContestOffice()
#
# self.assertEqual('wv01off922' in contest_office.we_vote_id, True,
# "contest_office retrieved does not have contest_office.we_vote_id='wv01off922'")
#
# #######################################
# # We should get a valid response
# response02 = self.client.get(self.candidates_retrieve_url, {'office_we_vote_id': contest_office.we_vote_id})
# json_data02 = json.loads(response02.content.decode())
#
# self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found")
# self.assertEqual('success' in json_data02, True, "success expected in the json response, and not found")
# self.assertEqual('office_id' in json_data02, True, "office_id expected in the json response, and not found")
# self.assertEqual('office_we_vote_id' in json_data02, True,
# "office_we_vote_id expected in the json response, and not found")
# self.assertEqual('google_civic_election_id' in json_data02, True,
# "google_civic_election_id expected in the json response, and not found")
# self.assertEqual('candidate_list' in json_data02, True,
# "candidate_list expected in the json response, and not found")
#
# self.assertEqual(
# json_data02['status'], 'CANDIDATES_RETRIEVED',
# "status: {status} (CANDIDATES_RETRIEVED expected), ".format(
# status=json_data02['status']))
# self.assertEqual(json_data02['success'], True, "success: {success} (success 'True' expected), ".format(
# success=json_data02['success']))
# # For this test we don't know what the internal office_id should be
# # self.assertEqual(json_data02['office_id'], 0, "office_id: {office_id} ('0' expected), ".format(
# # office_id=json_data02['office_id']))
# self.assertEqual(json_data02['office_we_vote_id'], 'wv01off922',
# "office_we_vote_id: {office_we_vote_id} ('wv01off922' expected), ".format(
# office_we_vote_id=json_data02['office_we_vote_id']))
# self.assertEqual(json_data02['google_civic_election_id'], '4162',
# "google_civic_election_id: {google_civic_election_id} ('4162' expected), ".format(
# google_civic_election_id=json_data02['google_civic_election_id']))
# self.assertEqual(len(json_data02['candidate_list']), 3,
# "len(candidate_list): {candidate_list_count} (3 candidates expected), ".format(
# candidate_list_count=len(json_data02['candidate_list'])))
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_candidates_retrieve.py",
"copies": "1",
"size": "6827",
"license": "mit",
"hash": 221185482149253950,
"line_mean": 61.6330275229,
"line_max": 118,
"alpha_frac": 0.6004101362,
"autogenerated": false,
"ratio": 3.799109627156372,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4899519763356372,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_organization_count.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from organization.models import Organization
class WeVoteAPIsV1TestsOrganizationCount(TestCase):
def setUp(self):
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_count_url = reverse("apis_v1:voterCountView")
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
def test_count_with_no_voter_device_id(self):
"""
This API should work even if person isn't signed in
:return:
"""
#######################################
# Check to see if there are 0 organizations
response = self.client.get(self.organization_count_url)
json_data = json.loads(response.content.decode())
self.assertEqual('success' in json_data, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data['organization_count'], 0,
"success: {success} (organization_count '0' expected), organization_count: {organization_count}".format(
success=json_data['success'], organization_count=json_data['organization_count']))
#######################################
# Add 3 organizations so we can check count again
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
organization2 = Organization.objects.create_organization_simple(
organization_name="Org2",
organization_website="www.org2.org",
organization_twitter_handle="org2",
)
organization3 = Organization.objects.create_organization_simple(
organization_name="Org3",
organization_website="www.org3.org",
organization_twitter_handle="org3",
)
#######################################
# Check to see if there are 3 organizations
response2 = self.client.get(self.organization_count_url)
json_data2 = json.loads(response2.content.decode())
self.assertEqual('success' in json_data2, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data2, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data2['organization_count'], 3,
"success: {success} (organization_count '3' expected), organization_count: {organization_count}".format(
success=json_data2['success'], organization_count=json_data2['organization_count']))
#######################################
# Remove data for 3 organizations
Organization.objects.delete_organization(organization_id=organization1.id)
Organization.objects.delete_organization(organization_id=organization2.id)
Organization.objects.delete_organization(organization_id=organization3.id)
#######################################
# Check to see if there are 0 organizations
response3 = self.client.get(self.organization_count_url)
json_data3 = json.loads(response3.content.decode())
self.assertEqual('success' in json_data3, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data3, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data3['organization_count'], 0,
"success: {success} (organization_count '0' expected - 2nd pass), "
"organization_count: {organization_count}".format(
success=json_data3['success'], organization_count=json_data3['organization_count']))
def test_count_with_voter_device_id(self):
"""
Test the various cookie states
:return:
"""
#######################################
# Generate the voter_device_id cookie
response0 = self.client.get(self.generate_voter_device_id_url)
json_data0 = json.loads(response0.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data0, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data0['voter_device_id'] if 'voter_device_id' in json_data0 else ''
#######################################
# Test for status: VOTER_CREATED
response02 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data02 = json.loads(response02.content.decode())
self.assertEqual('status' in json_data02, True,
"status expected in the voterCreateView json response but not found")
self.assertEqual('voter_device_id' in json_data02, True,
"voter_device_id expected in the voterCreateView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data02['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
status=json_data02['status'], voter_device_id=json_data02['voter_device_id']))
#######################################
# Check to see if there is 1 voter - i.e., the viewer
response11 = self.client.get(self.voter_count_url)
json_data11 = json.loads(response11.content.decode())
self.assertEqual('success' in json_data11, True, "'success' expected in the json response, and not found")
self.assertEqual('voter_count' in json_data11, True,
"'voter_count' expected in the organizationCount json response")
self.assertEqual(
json_data11['voter_count'], 1,
"success: {success} (voter_count '1' expected), voter_count: {voter_count}".format(
success=json_data11['success'], voter_count=json_data11['voter_count']))
#######################################
# Check to see if there are 0 organizations
response12 = self.client.get(self.organization_count_url)
json_data12 = json.loads(response12.content.decode())
self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data12, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data12['organization_count'], 0,
"success: {success} (organization_count '0' expected), organization_count: {organization_count}".format(
success=json_data12['success'], organization_count=json_data12['organization_count']))
#######################################
# Add 3 organizations so we can check count again
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
organization2 = Organization.objects.create_organization_simple(
organization_name="Org2",
organization_website="www.org2.org",
organization_twitter_handle="org2",
)
organization3 = Organization.objects.create_organization_simple(
organization_name="Org3",
organization_website="www.org3.org",
organization_twitter_handle="org3",
)
#######################################
# Check to see if there are 3 organizations
response22 = self.client.get(self.organization_count_url)
json_data22 = json.loads(response22.content.decode())
self.assertEqual('success' in json_data22, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data22, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data22['organization_count'], 3,
"success: {success} (organization_count '3' expected), organization_count: {organization_count}".format(
success=json_data22['success'], organization_count=json_data22['organization_count']))
#######################################
# Remove data for 3 organizations
Organization.objects.delete_organization(organization_id=organization1.id)
Organization.objects.delete_organization(organization_id=organization2.id)
Organization.objects.delete_organization(organization_id=organization3.id)
#######################################
# Check to see if there are 0 organizations
response23 = self.client.get(self.organization_count_url)
json_data23 = json.loads(response23.content.decode())
self.assertEqual('success' in json_data23, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data23, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data23['organization_count'], 0,
"success: {success} (organization_count '0' expected - 2nd pass), "
"organization_count: {organization_count}".format(
success=json_data23['success'], organization_count=json_data23['organization_count']))
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/tests/test_views_organization_count.py",
"copies": "2",
"size": "10244",
"license": "mit",
"hash": 182108065036742240,
"line_mean": 51,
"line_max": 116,
"alpha_frac": 0.6147012886,
"autogenerated": false,
"ratio": 4.390912987569653,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6005614276169653,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_organization_count.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.urls import reverse
from django.test import TestCase
import json
from organization.models import Organization
class WeVoteAPIsV1TestsOrganizationCount(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_count_url = reverse("apis_v1:voterCountView")
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
def test_count_with_no_voter_device_id(self):
"""
This API should work even if person isn't signed in
:return:
"""
#######################################
# Check to see if there are 0 organizations
response = self.client.get(self.organization_count_url)
json_data = json.loads(response.content.decode())
self.assertEqual('success' in json_data, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data['organization_count'], 0,
"success: {success} (organization_count '0' expected), organization_count: {organization_count}".format(
success=json_data['success'], organization_count=json_data['organization_count']))
#######################################
# Add 3 organizations so we can check count again
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
organization2 = Organization.objects.create_organization_simple(
organization_name="Org2",
organization_website="www.org2.org",
organization_twitter_handle="org2",
)
organization3 = Organization.objects.create_organization_simple(
organization_name="Org3",
organization_website="www.org3.org",
organization_twitter_handle="org3",
)
#######################################
# Check to see if there are 3 organizations
response2 = self.client.get(self.organization_count_url)
json_data2 = json.loads(response2.content.decode())
self.assertEqual('success' in json_data2, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data2, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data2['organization_count'], 3,
"success: {success} (organization_count '3' expected), organization_count: {organization_count}".format(
success=json_data2['success'], organization_count=json_data2['organization_count']))
#######################################
# Remove data for 3 organizations
Organization.objects.delete_organization(organization_id=organization1.id)
Organization.objects.delete_organization(organization_id=organization2.id)
Organization.objects.delete_organization(organization_id=organization3.id)
#######################################
# Check to see if there are 0 organizations
response3 = self.client.get(self.organization_count_url)
json_data3 = json.loads(response3.content.decode())
self.assertEqual('success' in json_data3, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data3, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data3['organization_count'], 0,
"success: {success} (organization_count '0' expected - 2nd pass), "
"organization_count: {organization_count}".format(
success=json_data3['success'], organization_count=json_data3['organization_count']))
def test_count_with_voter_device_id(self):
"""
Test the various cookie states
:return:
"""
#######################################
# Generate the voter_device_id cookie
response0 = self.client.get(self.generate_voter_device_id_url)
json_data0 = json.loads(response0.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data0, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data0['voter_device_id'] if 'voter_device_id' in json_data0 else ''
#######################################
# Test for status: VOTER_CREATED
response02 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data02 = json.loads(response02.content.decode())
self.assertEqual('status' in json_data02, True,
"status expected in the voterCreateView json response but not found")
self.assertEqual('voter_device_id' in json_data02, True,
"voter_device_id expected in the voterCreateView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data02['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
status=json_data02['status'], voter_device_id=json_data02['voter_device_id']))
#######################################
# Check to see if there is 1 voter - i.e., the viewer
response11 = self.client.get(self.voter_count_url)
json_data11 = json.loads(response11.content.decode())
self.assertEqual('success' in json_data11, True, "'success' expected in the json response, and not found")
self.assertEqual('voter_count' in json_data11, True,
"'voter_count' expected in the organizationCount json response")
self.assertEqual(
json_data11['voter_count'], 1,
"success: {success} (voter_count '1' expected), voter_count: {voter_count}".format(
success=json_data11['success'], voter_count=json_data11['voter_count']))
#######################################
# Check to see if there are 0 organizations
response12 = self.client.get(self.organization_count_url)
json_data12 = json.loads(response12.content.decode())
self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data12, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data12['organization_count'], 0,
"success: {success} (organization_count '0' expected), organization_count: {organization_count}".format(
success=json_data12['success'], organization_count=json_data12['organization_count']))
#######################################
# Add 3 organizations so we can check count again
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
organization2 = Organization.objects.create_organization_simple(
organization_name="Org2",
organization_website="www.org2.org",
organization_twitter_handle="org2",
)
organization3 = Organization.objects.create_organization_simple(
organization_name="Org3",
organization_website="www.org3.org",
organization_twitter_handle="org3",
)
#######################################
# Check to see if there are 3 organizations
response22 = self.client.get(self.organization_count_url)
json_data22 = json.loads(response22.content.decode())
self.assertEqual('success' in json_data22, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data22, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data22['organization_count'], 3,
"success: {success} (organization_count '3' expected), organization_count: {organization_count}".format(
success=json_data22['success'], organization_count=json_data22['organization_count']))
#######################################
# Remove data for 3 organizations
Organization.objects.delete_organization(organization_id=organization1.id)
Organization.objects.delete_organization(organization_id=organization2.id)
Organization.objects.delete_organization(organization_id=organization3.id)
#######################################
# Check to see if there are 0 organizations
response23 = self.client.get(self.organization_count_url)
json_data23 = json.loads(response23.content.decode())
self.assertEqual('success' in json_data23, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data23, True,
"'organization_count' expected in the organizationCount json response")
self.assertEqual(
json_data23['organization_count'], 0,
"success: {success} (organization_count '0' expected - 2nd pass), "
"organization_count: {organization_count}".format(
success=json_data23['success'], organization_count=json_data23['organization_count']))
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_organization_count.py",
"copies": "1",
"size": "10271",
"license": "mit",
"hash": -7955086373884550000,
"line_mean": 50.8737373737,
"line_max": 116,
"alpha_frac": 0.6142537241,
"autogenerated": false,
"ratio": 4.38931623931624,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5503569963416239,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_organization_follow.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from organization.models import Organization
class WeVoteAPIsV1TestsOrganizationFollow(TestCase):
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.organization_follow_url = reverse("apis_v1:organizationFollowView")
self.organization_follow_ignore_url = reverse("apis_v1:organizationFollowIgnoreView")
self.organization_stop_following_url = reverse("apis_v1:organizationStopFollowingView")
self.voter_count_url = reverse("apis_v1:voterCountView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
def test_follow_with_no_voter_device_id(self):
#######################################
# Make sure the correct errors are thrown when no one is signed in
response01 = self.client.get(self.organization_follow_url)
json_data01 = json.loads(response01.content.decode())
self.assertEqual('status' in json_data01, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data01, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data01, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data01, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data01['status'], 'VALID_VOTER_DEVICE_ID_MISSING',
"status: {status} (VALID_VOTER_DEVICE_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
status=json_data01['status'], voter_device_id=json_data01['voter_device_id']))
self.assertEqual(json_data01['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data01['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data01['organization_id']))
self.assertEqual(json_data01['voter_device_id'], '',
"voter_device_id == '' expected, voter_device_id: {voter_device_id} returned".format(
voter_device_id=json_data01['voter_device_id']))
#######################################
# Make sure the correct errors are thrown when no one is signed in
response02 = self.client.get(self.organization_follow_ignore_url)
json_data02 = json.loads(response02.content.decode())
self.assertEqual('status' in json_data02, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data02, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data02, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data02, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data02['status'], 'VALID_VOTER_DEVICE_ID_MISSING',
"status: {status} (VALID_VOTER_DEVICE_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
status=json_data02['status'], voter_device_id=json_data02['voter_device_id']))
self.assertEqual(json_data02['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data02['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data02['organization_id']))
self.assertEqual(json_data02['voter_device_id'], '',
"voter_device_id == '' expected, voter_device_id: {voter_device_id} returned".format(
voter_device_id=json_data02['voter_device_id']))
#######################################
# Make sure the correct errors are thrown when no one is signed in
response03 = self.client.get(self.organization_stop_following_url)
json_data03 = json.loads(response03.content.decode())
self.assertEqual('status' in json_data03, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data03, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data03, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data03, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data03['status'], 'VALID_VOTER_DEVICE_ID_MISSING',
"status: {status} (VALID_VOTER_DEVICE_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
status=json_data03['status'], voter_device_id=json_data03['voter_device_id']))
self.assertEqual(json_data03['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data03['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data03['organization_id']))
self.assertEqual(json_data03['voter_device_id'], '',
"voter_device_id == '' expected, voter_device_id: {voter_device_id} returned".format(
voter_device_id=json_data03['voter_device_id']))
def test_follow_with_voter_device_id(self):
#######################################
# Generate the voter_device_id cookie
response10 = self.client.get(self.generate_voter_device_id_url)
json_data10 = json.loads(response10.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data10, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data10['voter_device_id'] if 'voter_device_id' in json_data10 else ''
#######################################
# Create a voter so we can test retrieve
response11 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data11 = json.loads(response11.content.decode())
self.assertEqual('status' in json_data11, True,
"status expected in the voterOrganizationFollowView json response but not found")
self.assertEqual('voter_device_id' in json_data11, True,
"voter_device_id expected in the voterOrganizationFollowView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data11['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected in voterOrganizationFollowView), "
"voter_device_id: {voter_device_id}".format(
status=json_data11['status'], voter_device_id=json_data11['voter_device_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id isn't passed in
response12 = self.client.get(self.organization_follow_url, {'voter_device_id': voter_device_id})
json_data12 = json.loads(response12.content.decode())
self.assertEqual('status' in json_data12, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data12, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data12, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data12, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data12['status'], 'VALID_ORGANIZATION_ID_MISSING',
"status: {status} (VALID_ORGANIZATION_ID_MISSING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data12['status'], voter_device_id=json_data12['voter_device_id']))
self.assertEqual(json_data12['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data12['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data12['organization_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id isn't passed in
response13 = self.client.get(self.organization_follow_ignore_url, {'voter_device_id': voter_device_id})
json_data13 = json.loads(response13.content.decode())
self.assertEqual('status' in json_data13, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data13, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data13, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data13, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data13['status'], 'VALID_ORGANIZATION_ID_MISSING',
"status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
status=json_data13['status'], voter_device_id=json_data13['voter_device_id']))
self.assertEqual(json_data13['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data13['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data13['organization_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id isn't passed in
response14 = self.client.get(self.organization_stop_following_url, {'voter_device_id': voter_device_id})
json_data14 = json.loads(response14.content.decode())
self.assertEqual('status' in json_data14, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data14, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data14, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data14, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data14['status'], 'VALID_ORGANIZATION_ID_MISSING',
"status: {status} (VALID_ORGANIZATION_ID_MISSING expected), voter_device_id: {voter_device_id}".format(
status=json_data14['status'], voter_device_id=json_data14['voter_device_id']))
self.assertEqual(json_data14['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data14['organization_id'], 0,
"organization_id == 0 expected, organization_id: {organization_id} returned".format(
organization_id=json_data14['organization_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
response15 = self.client.get(self.organization_follow_url, {'organization_id': 1,
'voter_device_id': voter_device_id})
json_data15 = json.loads(response15.content.decode())
self.assertEqual('status' in json_data15, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data15, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data15, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data15, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data15['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING',
"status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOWING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data15['status'], voter_device_id=json_data15['voter_device_id']))
self.assertEqual(json_data15['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data15['organization_id'], 1,
"organization_id == 1 expected, organization_id: {organization_id} returned".format(
organization_id=json_data15['organization_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
response16 = self.client.get(self.organization_follow_ignore_url, {'organization_id': 1,
'voter_device_id': voter_device_id})
json_data16 = json.loads(response16.content.decode())
self.assertEqual('status' in json_data16, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data16, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data16, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data16, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data16['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE',
"status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE FOLLOW_IGNORE expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data16['status'], voter_device_id=json_data16['voter_device_id']))
self.assertEqual(json_data16['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data16['organization_id'], 1,
"organization_id == 1 expected, organization_id: {organization_id} returned".format(
organization_id=json_data16['organization_id']))
#######################################
# Make sure the correct errors are thrown when an organization_id is passed in for an org that doesn't exist
response17 = self.client.get(self.organization_stop_following_url, {'organization_id': 1,
'voter_device_id': voter_device_id})
json_data17 = json.loads(response17.content.decode())
self.assertEqual('status' in json_data17, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data17, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data17, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data17, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data17['status'], 'ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING',
"status: {status} (ORGANIZATION_NOT_FOUND_ON_CREATE STOP_FOLLOWING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data17['status'], voter_device_id=json_data17['voter_device_id']))
self.assertEqual(json_data17['success'], False, "success 'False' expected, True returned")
self.assertEqual(json_data17['organization_id'], 1,
"organization_id == 1 expected, organization_id: {organization_id} returned".format(
organization_id=json_data17['organization_id']))
#######################################
# Add an organization so we can test all of the 'follow' states
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
#######################################
# Make sure the correct results are given when saved successfully
response18 = self.client.get(self.organization_follow_url, {'organization_id': organization1.id,
'voter_device_id': voter_device_id})
json_data18 = json.loads(response18.content.decode())
self.assertEqual('status' in json_data18, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data18, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data18, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data18, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data18['status'], 'FOLLOWING',
"status: {status} (FOLLOWING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data18['status'], voter_device_id=json_data18['voter_device_id']))
self.assertEqual(json_data18['success'], True, "success 'True' expected, False returned")
self.assertEqual(json_data18['organization_id'], organization1.id,
"organization_id returned (organization_id: {organization_id}) didn't match"
"original passed in".format(
organization_id=json_data18['organization_id']))
#######################################
# Make sure the correct results are given when saved successfully
response19 = self.client.get(self.organization_follow_ignore_url, {'organization_id': organization1.id,
'voter_device_id': voter_device_id})
json_data19 = json.loads(response19.content.decode())
self.assertEqual('status' in json_data19, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data19, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data19, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data19, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data19['status'], 'IGNORING',
"status: {status} (IGNORING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data19['status'], voter_device_id=json_data19['voter_device_id']))
self.assertEqual(json_data19['success'], True, "success 'True' expected, False returned")
self.assertEqual(json_data19['organization_id'], organization1.id,
"organization_id returned (organization_id: {organization_id}) didn't match"
"original passed in".format(
organization_id=json_data19['organization_id']))
#######################################
# Make sure the correct results are given when saved successfully
response20 = self.client.get(self.organization_stop_following_url, {'organization_id': organization1.id,
'voter_device_id': voter_device_id})
json_data20 = json.loads(response20.content.decode())
self.assertEqual('status' in json_data20, True, "'status' expected in the json response, and not found")
self.assertEqual('success' in json_data20, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_id' in json_data20, True,
"'organization_id' expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data20, True,
"'voter_device_id' expected in the json response, and not found")
self.assertEqual(
json_data20['status'], 'STOPPED_FOLLOWING',
"status: {status} (STOPPED_FOLLOWING expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data20['status'], voter_device_id=json_data20['voter_device_id']))
self.assertEqual(json_data20['success'], True, "success 'True' expected, False returned")
self.assertEqual(json_data20['organization_id'], organization1.id,
"organization_id returned (organization_id: {organization_id}) didn't match"
"original passed in".format(
organization_id=json_data20['organization_id']))
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/tests/test_views_organization_follow.py",
"copies": "2",
"size": "22432",
"license": "mit",
"hash": 3879804061874503000,
"line_mean": 68.4489164087,
"line_max": 116,
"alpha_frac": 0.6077924394,
"autogenerated": false,
"ratio": 4.156383175838429,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00402596055417154,
"num_lines": 323
} |
# apis_v1/test_views_organization_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.urls import reverse
from django.test import TestCase
import json
from organization.models import Organization
class WeVoteAPIsV1TestsOrganizationRetrieve(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.organization_retrieve_url = reverse("apis_v1:organizationRetrieveView")
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_count_url = reverse("apis_v1:voterCountView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
def test_count_with_no_voter_device_id(self):
"""
This API should work even if person isn't signed in
:return:
"""
#######################################
# Check to see if there are 0 organizations
response = self.client.get(self.organization_count_url)
json_data = json.loads(response.content.decode())
self.assertEqual('success' in json_data, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data, True,
"'organization_count' expected in the organizationRetrieve json response")
self.assertEqual(
json_data['organization_count'], 0,
"success: {success} (organization_count '0' expected), organization_count: {organization_count}".format(
success=json_data['success'], organization_count=json_data['organization_count']))
#######################################
# Add 3 organizations so we can check count again
organization1 = Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
organization2 = Organization.objects.create_organization_simple(
organization_name="Org2",
organization_website="www.org2.org",
organization_twitter_handle="org2",
)
organization3 = Organization.objects.create_organization_simple(
organization_name="Org3",
organization_website="www.org3.org",
organization_twitter_handle="org3",
)
#######################################
# Check to see if there are 3 organizations
response2 = self.client.get(self.organization_count_url)
json_data2 = json.loads(response2.content.decode())
self.assertEqual('success' in json_data2, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data2, True,
"'organization_count' expected in the organizationRetrieve json response")
self.assertEqual(
json_data2['organization_count'], 3,
"success: {success} (organization_count '3' expected), organization_count: {organization_count}".format(
success=json_data2['success'], organization_count=json_data2['organization_count']))
#######################################
# Retrieve 1 organization without required variable
response3 = self.client.get(self.organization_retrieve_url)
json_data3 = json.loads(response3.content.decode())
self.assertEqual('success' in json_data3, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data3, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data3, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data3, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data3['success'], False,
"success: {success} (False expected)".format(
success=json_data3['success']))
self.assertIn(
'ORGANIZATION_RETRIEVE_BOTH_IDS_MISSING', json_data3['status'],
"success: {success} (status 'ORGANIZATION_RETRIEVE_BOTH_IDS_MISSING' expected, status={status})".format(
success=json_data3['success'], status=json_data3['status']))
#######################################
# Retrieve 1 organization with required organization_id
response4 = self.client.get(self.organization_retrieve_url, {'organization_id': organization1.id})
json_data4 = json.loads(response4.content.decode())
self.assertEqual('success' in json_data4, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data4, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data4, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data4, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data4['success'], True,
"success: {success} (True expected)".format(
success=json_data4['success']))
self.assertIn(
'ORGANIZATION_FOUND_WITH_ID', json_data4['status'],
"success: {success} (status 'ORGANIZATION_FOUND_WITH_ID' expected, status={status})".format(
success=json_data4['success'], status=json_data4['status']))
#######################################
# Retrieve 1 organization with required organization_we_vote_id
response5 = self.client.get(self.organization_retrieve_url,
{'organization_we_vote_id': organization1.we_vote_id})
json_data5 = json.loads(response5.content.decode())
self.assertEqual('success' in json_data5, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data5, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data5, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data5, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data5['success'], True,
"success: {success} (True expected)".format(
success=json_data5['success']))
self.assertIn(
'ORGANIZATION_FOUND_WITH_WE_VOTE_ID', json_data5['status'],
"success: {success} (status 'ORGANIZATION_FOUND_WITH_WE_VOTE_ID' expected, status={status})".format(
success=json_data5['success'], status=json_data5['status']))
#######################################
# Retrieve 1 organization with required organization_id even if organization_we_vote_id passed in
response6 = self.client.get(self.organization_retrieve_url,
{'organization_id': organization1.id,
'organization_we_vote_id': organization1.we_vote_id})
json_data6 = json.loads(response6.content.decode())
self.assertEqual('success' in json_data6, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data6, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data6, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data6, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data6['success'], True,
"success: {success} (True expected)".format(
success=json_data6['success']))
self.assertIn(
'ORGANIZATION_FOUND_WITH_ID', json_data6['status'],
"success: {success} (status 'ORGANIZATION_FOUND_WITH_ID' expected, status={status})".format(
success=json_data6['success'], status=json_data6['status']))
#######################################
# FAIL: Try to retrieve 1 organization with required organization_id that is wrong
response7 = self.client.get(self.organization_retrieve_url, {'organization_id': 888})
json_data7 = json.loads(response7.content.decode())
self.assertEqual('success' in json_data7, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data7, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data7, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data7, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data7['success'], False,
"success: {success} (False expected)".format(
success=json_data7['success']))
self.assertIn(
'RETRIEVING_ORGANIZATION_WITH_ID DOES_NOT_EXIST-ORGANIZATION_NOT_FOUND',
json_data7['status'].replace(' , ', ', '),
"success: {success} (status "
"'RETRIEVING_ORGANIZATION_WITH_ID DOES_NOT_EXIST-ORGANIZATION_NOT_FOUND' expected, "
"status={status})".format(
success=json_data7['success'], status=json_data7['status']))
#######################################
# FAIL: Try to retrieve 1 organization with required organization_id that is wrong
response8 = self.client.get(self.organization_retrieve_url, {'organization_we_vote_id': 'WV_Wrong'})
json_data8 = json.loads(response8.content.decode())
self.assertEqual('success' in json_data8, True,
"'success' variable expected in the organizationRetrieve json response, and not found")
self.assertEqual('organization_id' in json_data8, True,
"'organization_id' variable expected in the organizationRetrieve json response")
self.assertEqual('organization_we_vote_id' in json_data8, True,
"'organization_we_vote_id' variable expected in the organizationRetrieve json response")
self.assertEqual('status' in json_data8, True,
"'status' variable expected in the organizationRetrieve json response")
self.assertEqual(
json_data8['success'], False,
"success: {success} (False expected)".format(
success=json_data8['success']))
self.assertIn(
'RETRIEVING_ORGANIZATION_WITH_WE_VOTE_ID DOES_NOT_EXIST-ORGANIZATION_NOT_FOUND',
json_data8['status'].replace(' , ', ', '),
"success: {success} (status "
"'RETRIEVING_ORGANIZATION_WITH_WE_VOTE_ID DOES_NOT_EXIST-ORGANIZATION_NOT_FOUND' "
"expected, status={status})".format(
success=json_data8['success'], status=json_data8['status']))
# There shouldn't be any difference if there is a signed in voter or not
# def test_count_with_voter_device_id(self):
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_organization_retrieve.py",
"copies": "1",
"size": "12344",
"license": "mit",
"hash": 5098208909216038000,
"line_mean": 57.5023696682,
"line_max": 116,
"alpha_frac": 0.6129293584,
"autogenerated": false,
"ratio": 4.4969034608378875,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0022982034308945414,
"num_lines": 211
} |
# apis_v1/test_views_voter_address_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
import json
class WeVoteAPIsV1TestsVoterAddressRetrieve(TestCase):
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.voter_address_save_url = reverse("apis_v1:voterAddressSaveView")
self.voter_address_retrieve_url = reverse("apis_v1:voterAddressRetrieveView")
def test_retrieve_with_no_voter_device_id(self):
response = self.client.get(self.voter_address_retrieve_url)
json_data = json.loads(response.content.decode())
#######################################
# Without a cookie, we don't expect valid response
self.assertEqual('status' in json_data, True, "status expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data, True,
"voter_device_id expected in the voterAddressRetrieveView json response, and not found")
self.assertEqual(
json_data['status'], 'VALID_VOTER_DEVICE_ID_MISSING, GUESS_IF_NO_ADDRESS_SAVED, '
'VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_NOT_FOUND_FROM_IP: LOCATION_NOT_FOUND',
"status: {status} "
"('VALID_VOTER_DEVICE_ID_MISSING, GUESS_IF_NO_ADDRESS_SAVED, "
"VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_NOT_FOUND_FROM_IP: LOCATION_NOT_FOUND' expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data['status'], voter_device_id=json_data['voter_device_id']))
def test_retrieve_with_voter_device_id(self):
"""
Test the various cookie states
:return:
"""
#######################################
# Generate the voter_device_id cookie
response = self.client.get(self.generate_voter_device_id_url)
json_data = json.loads(response.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else ''
#######################################
# Create a voter so we can test retrieve
response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data2 = json.loads(response2.content.decode())
self.assertEqual('status' in json_data2, True,
"status expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('voter_device_id' in json_data2, True,
"voter_device_id expected in the voterAddressRetrieveView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data2['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected in voterAddressRetrieveView), "
"voter_device_id: {voter_device_id}".format(
status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))
#######################################
# Create a voter address so we can test retrieve
response3 = self.client.get(self.voter_address_save_url, {'text_for_map_search':
'123 Main Street, Oakland CA 94602',
'voter_device_id': voter_device_id})
json_data3 = json.loads(response3.content.decode())
self.assertEqual('status' in json_data3, True,
"status expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('voter_device_id' in json_data3, True,
"voter_device_id expected in the voterAddressRetrieveView json response but not found")
# First address save
self.assertEqual(
json_data3['text_for_map_search'], '123 Main Street, Oakland CA 94602',
"status: {status} ('123 Main Street, Oakland CA 94602'"
" expected in voterAddressRetrieveView), "
"voter_device_id: {voter_device_id}".format(
status=json_data3['status'], voter_device_id=json_data3['voter_device_id']))
#######################################
# Test for expected response variables
response4 = self.client.get(self.voter_address_retrieve_url, {'voter_device_id': voter_device_id})
json_data4 = json.loads(response4.content.decode())
# Are any expected fields missing?
self.assertEqual('success' in json_data4, True,
"success expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('text_for_map_search' in json_data4, True,
"text_for_map_search expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('address_type' in json_data4, True,
"address_type expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('latitude' in json_data4, True,
"latitude expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('longitude' in json_data4, True,
"longitude expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('normalized_line1' in json_data4, True,
"normalized_line1 expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('normalized_line2' in json_data4, True,
"normalized_line2 expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('normalized_city' in json_data4, True,
"normalized_city expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('normalized_state' in json_data4, True,
"normalized_state expected in the voterAddressRetrieveView json response but not found")
self.assertEqual('normalized_zip' in json_data4, True,
"normalized_zip expected in the voterAddressRetrieveView json response but not found")
# Does address match the value inserted last?
self.assertEqual(
json_data4['text_for_map_search'], '123 Main Street, Oakland CA 94602',
"text_for_map_search: {text_for_map_search} "
"('123 Main Street, Oakland CA 94602' expected in voterAddressRetrieveView), "
"voter_device_id: {voter_device_id}".format(
text_for_map_search=json_data4['text_for_map_search'], voter_device_id=json_data4['voter_device_id']))
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/tests/test_views_voter_address_retrieve.py",
"copies": "2",
"size": "7230",
"license": "bsd-3-clause",
"hash": 3518466451627186000,
"line_mean": 56.84,
"line_max": 118,
"alpha_frac": 0.6164591978,
"autogenerated": false,
"ratio": 4.003322259136213,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5619781456936213,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_voter_email_address_save.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.urls import reverse
from django.test import TestCase
from email_outbound.models import EmailAddress, EmailManager
import json
class WeVoteAPIsV1TestsVoterEmailAddressSave(TestCase):
databases = ["default", "readonly"]
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.voter_email_address_save_url = reverse("apis_v1:voterEmailAddressSaveView")
self.voter_email_address_retrieve_url = reverse("apis_v1:voterEmailAddressRetrieveView")
def test_save_with_no_voter_device_id(self):
response = self.client.post(self.voter_email_address_save_url)
json_data = json.loads(response.content.decode())
#######################################
# Without a cookie, we don't expect valid response
self.assertEqual('status' in json_data, True, "status expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data, True,
"voter_device_id expected in the voterEmailAddressSaveView json response, and not found")
self.assertEqual(json_data['status'],
"VOTER_EMAIL_ADDRESS_SAVE-START VALID_VOTER_DEVICE_ID_MISSING VOTER_DEVICE_ID_NOT_VALID ",
"status: {status} ('VOTER_EMAIL_ADDRESS_SAVE-START VALID_VOTER_DEVICE_ID_MISSING VOTER_DEVICE_ID_NOT_VALID' expected), "
"voter_device_id: {voter_device_id}".format(status=json_data['status'],
voter_device_id=json_data['voter_device_id']))
def test_save_with_voter_device_id(self):
#######################################
# Generate the voter_device_id cookie
response = self.client.get(self.generate_voter_device_id_url)
json_data = json.loads(response.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else ''
#######################################
# Create a voter so we can test retrieve
response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data2 = json.loads(response2.content.decode())
self.assertEqual('status' in json_data2, True,
"status expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('voter_device_id' in json_data2, True,
"voter_device_id expected in the voterEmailAddressSaveView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data2['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected in voterEmailAddressSaveView), "
"voter_device_id: {voter_device_id}".format(
status=json_data2['status'], voter_device_id=json_data2['voter_device_id']))
#######################################
# Create a voter email address so we can test retrieve
response2 = self.client.get(self.voter_email_address_save_url, {'text_for_email_address':
'test123@gmail.com',
'voter_device_id': voter_device_id})
json_data2 = json.loads(response2.content.decode())
self.assertEqual('status' in json_data2, True,
"status expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('voter_device_id' in json_data2, True,
"voter_device_id expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('success' in json_data2, True,
"success expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('text_for_email_address' in json_data2, True,
"address expected in the voterEmailAddressSaveView json response but not found")
# First voter email address save
self.assertEqual(json_data2['status'],
"VOTER_EMAIL_ADDRESS_SAVE-START CREATE_NEW_EMAIL_ADDRESS EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_OUTBOUND_DESCRIPTION_CREATED SCHEDULE_EMAIL_CREATED EMAIL_SCHEDULED ",
"status: {status} ('VOTER_EMAIL_ADDRESS_SAVE-START CREATE_NEW_EMAIL_ADDRESS EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_OUTBOUND_DESCRIPTION_CREATED SCHEDULE_EMAIL_CREATED EMAIL_SCHEDULED ' expected), "
"voter_device_id: {voter_device_id}".format(status=json_data2['status'],
voter_device_id=json_data2['voter_device_id']))
# Try and save the voter email address again
response3 = self.client.get(self.voter_email_address_save_url, {'text_for_email_address':
'test321@gmail.com',
'voter_device_id': voter_device_id})
json_data3 = json.loads(response3.content.decode())
self.assertEqual(json_data3['status'],
"VOTER_EMAIL_ADDRESS_SAVE-START CREATE_NEW_EMAIL_ADDRESS EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_OUTBOUND_DESCRIPTION_CREATED SCHEDULE_EMAIL_CREATED EMAIL_SCHEDULED ",
"status: {status} ('VOTER_EMAIL_ADDRESS_SAVE-START CREATE_NEW_EMAIL_ADDRESS EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_ADDRESS_FOR_VOTER_CREATED EMAIL_OUTBOUND_DESCRIPTION_CREATED SCHEDULE_EMAIL_CREATED EMAIL_SCHEDULED ' expected), "
"voter_device_id: {voter_device_id}".format(status=json_data3['status'],
voter_device_id=json_data3['voter_device_id']))
######################################################################
# Test to make sure the email address has been saved in the database
response4 = self.client.get(self.voter_email_address_retrieve_url, {'voter_device_id': voter_device_id})
json_data4 = json.loads(response4.content.decode())
# Are any expected fields missing?
self.assertEqual('status' in json_data4, True,
"status expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('voter_device_id' in json_data4, True,
"voter_device_id expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('success' in json_data4, True,
"success expected in the voterEmailAddressSaveView json response but not found")
self.assertEqual('email_address_list' in json_data4, True,
"email_address_list expected in the voterEmailAddressSaveView json response but not found")
# A more thorough testing of expected variables is done in test_views_voter_email_address_retrieve.py
# Confirm that we have two email addresses for this user
self.assertEqual(
len(json_data4['email_address_list']), 2,
"Length of email_address_list:{email_address_list_length} (expected to be 2), "
"voter_device_id: {voter_device_id}".format(
email_address_list_length=len(json_data4['email_address_list']), voter_device_id=json_data4['voter_device_id']))
######################################################################
# Now try to save an invalid email address
response5 = self.client.get(self.voter_email_address_save_url, {'text_for_email_address':
'test321gmail.com',
'voter_device_id': voter_device_id})
json_data5 = json.loads(response5.content.decode())
self.assertEqual(json_data5['status'],
"VOTER_EMAIL_ADDRESS_SAVE-START VOTER_EMAIL_ADDRESS_SAVE_MISSING_VALID_EMAIL ",
"status: {status} ('VOTER_EMAIL_ADDRESS_SAVE-START VOTER_EMAIL_ADDRESS_SAVE_MISSING_VALID_EMAIL ' expected), "
"voter_device_id: {voter_device_id}".format(status=json_data5['status'],
voter_device_id=json_data5['voter_device_id']))
self.assertEqual(json_data5['email_address_not_valid'],
True,
"email_address_not_valid: {email_address_not_valid} ('True' expected), "
"voter_device_id: {voter_device_id}".format(email_address_not_valid=json_data5['email_address_not_valid'],
voter_device_id=json_data5['voter_device_id'])) | {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/tests/test_views_voter_email_address_save.py",
"copies": "1",
"size": "9236",
"license": "mit",
"hash": 4900110462402552000,
"line_mean": 63.1458333333,
"line_max": 242,
"alpha_frac": 0.6069727155,
"autogenerated": false,
"ratio": 3.9707652622527947,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5077737977752794,
"avg_score": null,
"num_lines": null
} |
# apis_v1/test_views_voter_guides_to_follow_retrieve.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
import json
from organization.models import Organization
class WeVoteAPIsV1TestsVoterGuidesToFollowRetrieve(TestCase):
def setUp(self):
self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView")
self.organization_count_url = reverse("apis_v1:organizationCountView")
self.voter_create_url = reverse("apis_v1:voterCreateView")
self.voter_guides_to_follow_retrieve_url = reverse("apis_v1:voterGuidesToFollowRetrieveView")
def test_retrieve_with_no_voter_device_id(self):
#######################################
# Without a cookie, we don't expect valid response
response = self.client.get(self.voter_guides_to_follow_retrieve_url)
json_data = json.loads(response.content.decode())
self.assertEqual('status' in json_data, True, "status expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data, True,
"voter_device_id expected in the voterGuidesToFollowRetrieveView json response, and not found")
self.assertEqual(
json_data['status'], 'ERROR_GUIDES_TO_FOLLOW_NO_VOTER_DEVICE_ID',
"status: {status} (ERROR_GUIDES_TO_FOLLOW_NO_VOTER_DEVICE_ID expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data['status'], voter_device_id=json_data['voter_device_id']))
def test_retrieve_with_voter_device_id(self):
"""
Test the various cookie states
:return:
"""
#######################################
# Generate the voter_device_id cookie
response01 = self.client.get(self.generate_voter_device_id_url)
json_data01 = json.loads(response01.content.decode())
# Make sure we got back a voter_device_id we can use
self.assertEqual('voter_device_id' in json_data01, True,
"voter_device_id expected in the deviceIdGenerateView json response")
# Now put the voter_device_id in a variable we can use below
voter_device_id = json_data01['voter_device_id'] if 'voter_device_id' in json_data01 else ''
#######################################
# With a cookie, but without a voter_id in the database, we don't expect valid response
response02 = self.client.get(self.voter_guides_to_follow_retrieve_url, {'voter_device_id': voter_device_id})
json_data02 = json.loads(response02.content.decode())
self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found")
self.assertEqual('voter_device_id' in json_data02, True,
"voter_device_id expected in the voterGuidesToFollowRetrieveView json response, and not found")
self.assertEqual(
json_data02['status'], 'ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID',
"status: {status} (ERROR_GUIDES_TO_FOLLOW_VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data02['status'], voter_device_id=json_data02['voter_device_id']))
#######################################
# Create a voter so we can test retrieve
response03 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})
json_data03 = json.loads(response03.content.decode())
self.assertEqual('status' in json_data03, True,
"status expected in the voterCreateView json response but not found")
self.assertEqual('voter_device_id' in json_data03, True,
"voter_device_id expected in the voterCreateView json response but not found")
# With a brand new voter_device_id, a new voter record should be created
self.assertEqual(
json_data03['status'], 'VOTER_CREATED',
"status: {status} (VOTER_CREATED expected), voter_device_id: {voter_device_id}".format(
status=json_data03['status'], voter_device_id=json_data03['voter_device_id']))
#######################################
# Test the response before any voter guides exist
response04 = self.client.get(self.voter_guides_to_follow_retrieve_url, {'voter_device_id': voter_device_id})
json_data04 = json.loads(response04.content.decode())
self.assertEqual('status' in json_data04, True,
"status expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('success' in json_data04, True,
"success expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('voter_device_id' in json_data04, True,
"voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('voter_guides' in json_data04, True,
"voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual(
json_data04['status'], 'SUCCESSFUL_RETRIEVE_OF_VOTER_GUIDES_GENERIC NO_VOTER_GUIDES_FOUND',
"status: {status} ('SUCCESSFUL_RETRIEVE_OF_VOTER_GUIDES_GENERIC NO_VOTER_GUIDES_FOUND' expected), "
"voter_device_id: {voter_device_id}".format(
status=json_data04['status'], voter_device_id=json_data04['voter_device_id']))
#######################################
# Create organization
Organization.objects.create_organization_simple(
organization_name="Org1",
organization_website="www.org1.org",
organization_twitter_handle="org1",
)
#######################################
# Check to make sure there is 1 organization
response10 = self.client.get(self.organization_count_url)
json_data10 = json.loads(response10.content.decode())
self.assertEqual('success' in json_data10, True, "'success' expected in the json response, and not found")
self.assertEqual('organization_count' in json_data10, True,
"'organization_count' expected in the organizationRetrieve json response")
self.assertEqual(
json_data10['organization_count'], 1,
"success: {success} (organization_count '1' expected), organization_count: {organization_count}".format(
success=json_data10['success'], organization_count=json_data10['organization_count']))
#######################################
# Create candidate_campaign
#######################################
# Create position where organization is supporting candidate
#######################################
# Test the response with one voter guide
response40 = self.client.get(self.voter_guides_to_follow_retrieve_url, {'voter_device_id': voter_device_id})
json_data40 = json.loads(response40.content.decode())
self.assertEqual('status' in json_data40, True,
"status expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('success' in json_data40, True,
"success expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('voter_device_id' in json_data40, True,
"voter_device_id expected in the voterGuidesToFollowRetrieveView json response but not found")
self.assertEqual('voter_guides' in json_data40, True,
"voter_guides expected in the voterGuidesToFollowRetrieveView json response but not found")
# Make sure all voter guides returned have the expected array keys
for one_voter_guide in json_data40['voter_guides']:
self.assertEqual('google_civic_election_id' in one_voter_guide, True,
"google_civic_election_id expected in voterGuidesToFollowRetrieveView json but not found")
self.assertEqual('voter_guide_owner_type' in one_voter_guide, True,
"voter_guide_owner_type expected in voterGuidesToFollowRetrieveView json but not found")
self.assertEqual('organization_we_vote_id' in one_voter_guide, True,
"organization_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found")
self.assertEqual('public_figure_we_vote_id' in one_voter_guide, True,
"public_figure_we_vote_id expected in voterGuidesToFollowRetrieveView json but not found")
self.assertEqual('owner_voter_id' in one_voter_guide, True,
"owner_voter_id expected in voterGuidesToFollowRetrieveView json but not found")
self.assertEqual('last_updated' in one_voter_guide, True,
"last_updated expected in voterGuidesToFollowRetrieveView json but not found")
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/tests/test_views_voter_guides_to_follow_retrieve.py",
"copies": "2",
"size": "9241",
"license": "mit",
"hash": 2242157543452405200,
"line_mean": 58.2371794872,
"line_max": 120,
"alpha_frac": 0.6264473542,
"autogenerated": false,
"ratio": 3.9883470004315926,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0029062475363412135,
"num_lines": 156
} |
# apis_v1/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
"""
This is called from config/urls.py like this:
url(r'^apis/v1/', include('apis_v1.urls', namespace="apis_v1")),
"""
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from apis_v1.views import views_docs, views_analytics, views_ballot, views_candidate, views_donation, \
views_election, views_facebook, views_friend, views_issues, views_misc, views_organization, \
views_pledge_to_vote, views_position, views_twitter, views_voter, views_voter_guide
from ballot.views_admin import ballot_items_sync_out_view, ballot_returned_sync_out_view
from candidate.views_admin import candidates_sync_out_view
from issue.views_admin import issues_sync_out_view, issues_retrieve_view, retrieve_issues_to_follow_view, \
organization_link_to_issue_sync_out_view, test_real_time_update
from measure.views_admin import measures_sync_out_view
from office.views_admin import offices_sync_out_view
from organization.views_admin import organizations_sync_out_view
from politician.views_admin import politicians_sync_out_view
from polling_location.views_admin import polling_locations_sync_out_view
from position.views_admin import positions_sync_out_view
from voter_guide.views_admin import voter_guides_sync_out_view
urlpatterns = [
# Actual API Calls
url(r'^ballotItemOptionsRetrieve/', views_ballot.ballot_item_options_retrieve_view,
name='ballotItemOptionsRetrieveView'),
url(r'^ballotItemRetrieve/', views_ballot.ballot_item_retrieve_view, name='ballotItemRetrieveView'),
url(r'^ballotItemsSyncOut/', ballot_items_sync_out_view, name='ballotItemsSyncOutView'),
url(r'^ballotReturnedSyncOut/', ballot_returned_sync_out_view, name='ballotReturnedSyncOutView'),
url(r'^candidateRetrieve/', views_candidate.candidate_retrieve_view, name='candidateRetrieveView'),
url(r'^candidatesRetrieve/', views_candidate.candidates_retrieve_view, name='candidatesRetrieveView'),
url(r'^candidatesSyncOut/', candidates_sync_out_view, name='candidatesSyncOutView'),
url(r'^deviceIdGenerate/$', views_misc.device_id_generate_view, name='deviceIdGenerateView'),
url(r'^donationCancelSubscription',
views_donation.donation_cancel_subscription_view, name='donationCancelSubscription'),
url(r'^donationRefund', views_donation.donation_refund_view, name='donationRefund'),
url(r'^donationStripeWebhook/', views_donation.donation_stripe_webhook_view, name='donationStripeWebhookView'),
url(r'^donationWithStripe', views_donation.donation_with_stripe_view, name='donationWithStripeView'),
url(r'^electionsRetrieve/', views_election.elections_retrieve_view, name='electionsRetrieveView'),
url(r'^electionsSyncOut/', views_election.elections_sync_out_view, name='electionsSyncOutView'),
url(r'^emailBallotData/', views_ballot.email_ballot_data_view, name='emailBallotDataView'),
url(r'^facebookDisconnect/', views_facebook.facebook_disconnect_view, name='facebookDisconnectView'),
url(r'^facebookFriendsAction/', views_facebook.facebook_friends_action_view, name='facebookFriendsActionView'),
url(r'^friendInvitationByEmailSend/',
views_friend.friend_invitation_by_email_send_view, name='friendInvitationByEmailSendView'),
url(r'^friendInvitationByEmailVerify/',
views_friend.friend_invitation_by_email_verify_view, name='friendInvitationByEmailVerifyView'),
url(r'^friendInvitationByFacebookSend/',
views_friend.friend_invitation_by_facebook_send_view, name='friendInvitationByFacebookSendView'),
url(r'^friendInvitationByFacebookVerify/',
views_friend.friend_invitation_by_facebook_verify_view, name='friendInvitationByFacebookVerifyView'),
url(r'^friendInvitationByWeVoteIdSend/',
views_friend.friend_invitation_by_we_vote_id_send_view, name='friendInvitationByWeVoteIdSendView'),
url(r'^friendInviteResponse/', views_friend.friend_invite_response_view, name='friendInviteResponseView'),
url(r'^friendList/', views_friend.friend_list_view, name='friendListView'),
url(r'^issueFollow/', views_voter.voter_issue_follow_view, name='issueFollowView'),
url(r'^issuesLinkedToOrganization/', views_issues.issues_linked_to_organization_view,
name='issuesLinkedToOrganizationView'),
url(r'^issuesToLinkToForOrganization/', views_issues.issues_to_link_to_for_organization_view,
name='issuesToLinkToForOrganizationView'),
url(r'^issuesRetrieve/', issues_retrieve_view, name='issuesRetrieveView'),
url(r'^issuesSyncOut/', issues_sync_out_view, name='issuesSyncOutView'),
url(r'^measureRetrieve/', views_misc.measure_retrieve_view, name='measureRetrieveView'),
url(r'^measuresSyncOut/', measures_sync_out_view, name='measuresSyncOutView'),
url(r'^officeRetrieve/', views_misc.office_retrieve_view, name='officeRetrieveView'),
url(r'^officesSyncOut/', offices_sync_out_view, name='officesSyncOutView'),
url(r'^organizationCount/', views_organization.organization_count_view, name='organizationCountView'),
url(r'^organizationFollow/', views_organization.organization_follow_api_view, name='organizationFollowView'),
url(r'^organizationFollowIgnore/', views_organization.organization_follow_ignore_api_view,
name='organizationFollowIgnoreView'),
url(r'^organizationLinkToIssueSyncOut/',
organization_link_to_issue_sync_out_view, name='organizationLinkToIssueSyncOutView'),
url(r'^organizationLinkToIssue/', views_issues.organization_link_to_issue_view, name='organizationLinkToIssueView'),
url(r'^organizationRetrieve/', views_organization.organization_retrieve_view, name='organizationRetrieveView'),
url(r'^organizationSave/', views_organization.organization_save_view, name='organizationSaveView'),
url(r'^organizationSearch/', views_organization.organization_search_view, name='organizationSearchView'),
url(r'^organizationsSyncOut/', organizations_sync_out_view, name='organizationsSyncOutView'),
url(r'^organizationStopFollowing/',
views_organization.organization_stop_following_api_view, name='organizationStopFollowingView'),
url(r'^organizationsFollowedRetrieve/',
views_organization.organizations_followed_retrieve_api_view, name='organizationsFollowedRetrieveView'),
url(r'^organizationSuggestionTasks/',
views_organization.organization_suggestion_tasks_view, name='organizationSuggestionTasksView'),
url(r'^pledgeToVoteWithVoterGuide/',
views_pledge_to_vote.pledge_to_vote_with_voter_guide_view, name='pledgeToVoteWithVoterGuideView'),
url(r'^politiciansSyncOut/', politicians_sync_out_view, name='politiciansSyncOutView'),
url(r'^pollingLocationsSyncOut/', polling_locations_sync_out_view, name='pollingLocationsSyncOutView'),
url(r'^positionsCountForAllBallotItems/',
views_position.positions_count_for_all_ballot_items_view, name='positionsCountForAllBallotItemsView'),
url(r'^positionsCountForOneBallotItem/',
views_position.positions_count_for_one_ballot_item_view, name='positionsCountForOneBallotItemView'),
url(r'^positionLikeCount/', views_position.position_like_count_view, name='positionLikeCountView'),
url(r'^positionListForBallotItem/', views_position.position_list_for_ballot_item_view,
name='positionListForBallotItemView'),
url(r'^positionListForOpinionMaker/',
views_position.position_list_for_opinion_maker_view, name='positionListForOpinionMakerView'),
url(r'^positionListForVoter/',
views_position.position_list_for_voter_view, name='positionListForVoterView'),
url(r'^positionOpposeCountForBallotItem/',
views_position.position_oppose_count_for_ballot_item_view, name='positionOpposeCountForBallotItemView'),
url(r'^positionPublicOpposeCountForBallotItem/',
views_position.position_public_oppose_count_for_ballot_item_view,
name='positionPublicOpposeCountForBallotItemView'),
url(r'^positionPublicSupportCountForBallotItem/',
views_position.position_public_support_count_for_ballot_item_view,
name='positionPublicSupportCountForBallotItemView'),
url(r'^positionRetrieve/', views_position.position_retrieve_view, name='positionRetrieveView'),
url(r'^positionSave/', views_position.position_save_view, name='positionSaveView'),
url(r'^positionsSyncOut/', positions_sync_out_view, name='positionsSyncOutView'),
url(r'^positionSupportCountForBallotItem/',
views_position.position_support_count_for_ballot_item_view, name='positionSupportCountForBallotItemView'),
url(r'^quickInfoRetrieve/', views_misc.quick_info_retrieve_view, name='quickInfoRetrieveView'),
url(r'^retrieveIssuesToFollow/', retrieve_issues_to_follow_view, name='retrieveIssuesToFollowView'),
url(r'^saveAnalyticsAction/', views_analytics.save_analytics_action_view, name='saveAnalyticsActionView'),
url(r'^searchAll/', views_misc.search_all_view, name='searchAllView'),
url(r'^testRealTimeUpdate/', test_real_time_update, name='testRealTimeUpdate'),
url(r'^twitterIdentityRetrieve/', views_twitter.twitter_identity_retrieve_view, name='twitterIdentityRetrieveView'),
url(r'^twitterNativeSignInSave/', views_twitter.twitter_native_sign_in_save_view, name='twitterNativeSignInSave'),
url(r'^twitterSignInRequestAccessToken/',
views_twitter.twitter_sign_in_request_access_token_view, name='twitterSignInRequestAccessTokenView'),
url(r'^twitterSignInRequestVoterInfo/',
views_twitter.twitter_sign_in_request_voter_info_view, name='twitterSignInRequestVoterInfoView'),
url(r'^twitterSignInStart/', views_twitter.twitter_sign_in_start_view, name='twitterSignInStartView'),
url(r'^twitterSignInRetrieve/', views_twitter.twitter_sign_in_retrieve_view, name='twitterSignInRetrieveView'),
url(r'^twitterRetrieveIdsIFollow/',
views_twitter.twitter_retrieve_ids_i_follow_view, name='twitterRetrieveIdsIFollowView'),
url(r'^voterAddressRetrieve/', views_voter.voter_address_retrieve_view, name='voterAddressRetrieveView'),
url(r'^voterAddressSave/', views_voter.voter_address_save_view, name='voterAddressSaveView'),
url(r'^voterAllPositionsRetrieve/', views_voter.voter_all_positions_retrieve_view,
name='voterAllPositionsRetrieveView'),
url(r'^voterAllBookmarksStatusRetrieve/',
views_voter.voter_all_bookmarks_status_retrieve_view, name='voterAllBookmarksStatusRetrieveView'),
url(r'^voterBallotItemsRetrieve/', views_voter.voter_ballot_items_retrieve_view,
name='voterBallotItemsRetrieveView'),
url(r'^voterBallotItemsRetrieveFromGoogleCivic/',
views_voter.voter_ballot_items_retrieve_from_google_civic_view,
name='voterBallotItemsRetrieveFromGoogleCivicView'),
url(r'^voterBallotListRetrieve/', views_voter.voter_ballot_list_retrieve_view, name='voterBallotListRetrieveView'),
url(r'^voterBookmarkOffSave/', views_voter.voter_bookmark_off_save_view, name='voterBookmarkOffSaveView'),
url(r'^voterBookmarkOnSave/', views_voter.voter_bookmark_on_save_view, name='voterBookmarkOnSaveView'),
url(r'^voterBookmarkStatusRetrieve/', views_voter.voter_bookmark_status_retrieve_view,
name='voterBookmarkStatusRetrieveView'),
url(r'^voterCount/', views_voter.voter_count_view, name='voterCountView'),
url(r'^voterCreate/', views_voter.voter_create_view, name='voterCreateView'),
url(r'^voterEmailAddressRetrieve/', views_voter.voter_email_address_retrieve_view,
name='voterEmailAddressRetrieveView'),
url(r'^voterEmailAddressSave/', views_voter.voter_email_address_save_view, name='voterEmailAddressSaveView'),
url(r'^voterEmailAddressSignIn/', views_voter.voter_email_address_sign_in_view, name='voterEmailAddressSignInView'),
url(r'^voterEmailAddressVerify/', views_voter.voter_email_address_verify_view, name='voterEmailAddressVerifyView'),
url(r'^voterFacebookSaveToCurrentAccount/',
views_facebook.voter_facebook_save_to_current_account_view, name='voterFacebookSaveToCurrentAccountView'),
url(r'^voterFacebookSignInRetrieve/',
views_voter.voter_facebook_sign_in_retrieve_view, name='voterFacebookSignInRetrieveView'),
url(r'^voterFacebookSignInSave/',
views_voter.voter_facebook_sign_in_save_view, name='voterFacebookSignInSaveView'),
url(r'^voterFollowAllOrganizationsFollowedByOrganization/',
views_voter.voter_follow_all_organizations_followed_by_organization_view,
name='voterFollowAllOrganizationsFollowedByOrganizationView'),
url(r'^voterGuidePossibilityRetrieve/',
views_voter_guide.voter_guide_possibility_retrieve_view, name='voterGuidePossibilityRetrieveView'),
url(r'^voterGuidePossibilitySave/', views_voter_guide.voter_guide_possibility_save_view,
name='voterGuidePossibilitySaveView'),
url(r'^voterGuidesFollowedRetrieve/',
views_voter_guide.voter_guides_followed_retrieve_view, name='voterGuidesFollowedRetrieveView'),
url(r'^voterGuidesFollowedByOrganizationRetrieve/',
views_voter_guide.voter_guides_followed_by_organization_retrieve_view,
name='voterGuidesFollowedByOrganizationRetrieveView'),
url(r'^voterGuideFollowersRetrieve/',
views_voter_guide.voter_guide_followers_retrieve_view, name='voterGuideFollowersRetrieveView'),
url(r'^voterGuidesIgnoredRetrieve/',
views_voter_guide.voter_guides_ignored_retrieve_view, name='voterGuidesIgnoredRetrieveView'),
url(r'^voterGuideSave/',
views_voter_guide.voter_guide_save_view, name='voterGuideSaveView'),
url(r'^voterGuidesRetrieve/',
views_voter_guide.voter_guides_retrieve_view, name='voterGuidesRetrieveView'),
url(r'^voterGuidesSyncOut/', voter_guides_sync_out_view, name='voterGuidesSyncOutView'),
url(r'^voterGuidesToFollowRetrieve/',
views_voter_guide.voter_guides_to_follow_retrieve_view, name='voterGuidesToFollowRetrieveView'),
url(r'^voterGuidesUpcomingRetrieve/',
views_voter_guide.voter_guides_upcoming_retrieve_view, name='voterGuidesUpcomingRetrieveView'),
url(r'^voterLocationRetrieveFromIP/',
views_voter.voter_location_retrieve_from_ip_view, name='voterLocationRetrieveFromIPView'),
url(r'^voterMergeTwoAccounts/', views_voter.voter_merge_two_accounts_view, name='voterMergeTwoAccountsView'),
url(r'^voterOpposingSave/', views_voter.voter_opposing_save_view, name='voterOpposingSaveView'),
url(r'^voterPhotoSave/', views_voter.voter_photo_save_view, name='voterPhotoSaveView'),
url(r'^voterPositionCommentSave/', views_voter.voter_position_comment_save_view,
name='voterPositionCommentSaveView'),
url(r'^voterPositionLikeOffSave/', views_voter.voter_position_like_off_save_view,
name='voterPositionLikeOffSaveView'),
url(r'^voterPositionLikeOnSave/', views_voter.voter_position_like_on_save_view,
name='voterPositionLikeOnSaveView'),
url(r'^voterPositionLikeStatusRetrieve/',
views_voter.voter_position_like_status_retrieve_view, name='voterPositionLikeStatusRetrieveView'),
url(r'^voterPositionRetrieve/', views_voter.voter_position_retrieve_view, name='voterPositionRetrieveView'),
url(r'^voterPositionVisibilitySave/',
views_voter.voter_position_visibility_save_view, name='voterPositionVisibilitySaveView'),
url(r'^voterRetrieve/', views_voter.voter_retrieve_view, name='voterRetrieveView'),
url(r'^voterSignOut/', views_voter.voter_sign_out_view, name='voterSignOutView'),
url(r'^voterSplitIntoTwoAccounts/',
views_voter.voter_split_into_two_accounts_view, name='voterSplitIntoTwoAccountsView'),
url(r'^voterStopOpposingSave/', views_voter.voter_stop_opposing_save_view, name='voterStopOpposingSaveView'),
url(r'^voterStopSupportingSave/', views_voter.voter_stop_supporting_save_view, name='voterStopSupportingSaveView'),
url(r'^voterSupportingSave/', views_voter.voter_supporting_save_view, name='voterSupportingSaveView'),
url(r'^voterTwitterSaveToCurrentAccount/',
views_voter.voter_twitter_save_to_current_account_view, name='voterTwitterSaveToCurrentAccountView'),
url(r'^voterUpdate/', views_voter.voter_update_view, name='voterUpdateView'),
##########################
# API Documentation Views
url(r'^docs/$', views_docs.apis_index_doc_view, name='apisIndex'),
url(r'^docs/ballotItemOptionsRetrieve/$',
views_docs.ballot_item_options_retrieve_doc_view, name='ballotItemOptionsRetrieveDocs'),
url(r'^docs/ballotItemRetrieve/$', views_docs.ballot_item_retrieve_doc_view, name='ballotItemRetrieveDocs'),
url(r'^docs/ballotItemsSyncOut/$', views_docs.ballot_items_sync_out_doc_view, name='ballotItemsSyncOutDocs'),
url(r'^docs/ballotReturnedSyncOut/$',
views_docs.ballot_returned_sync_out_doc_view, name='ballotReturnedSyncOutDocs'),
url(r'^docs/candidateRetrieve/$', views_docs.candidate_retrieve_doc_view, name='candidateRetrieveDocs'),
url(r'^docs/candidatesRetrieve/$', views_docs.candidates_retrieve_doc_view, name='candidatesRetrieveDocs'),
url(r'^docs/candidatesSyncOut/$', views_docs.candidates_sync_out_doc_view, name='candidatesSyncOutDocs'),
url(r'^docs/deviceIdGenerate/$', views_docs.device_id_generate_doc_view, name='deviceIdGenerateDocs'),
url(r'^docs/donationWithStripe/$', views_docs.donation_with_stripe_doc_view, name='donationWithStripeDocs'),
url(r'^docs/electionsRetrieve/$', views_docs.elections_retrieve_doc_view, name='electionsRetrieveDocs'),
url(r'^docs/electionsSyncOut/$', views_docs.elections_sync_out_doc_view, name='electionsSyncOutDocs'),
url(r'^docs/facebookDisconnect/$', views_docs.facebook_disconnect_doc_view, name='facebookDisconnectDocs'),
url(r'^docs/emailBallotData/$', views_docs.email_ballot_data_doc_view, name='emailBallotDataDocs'),
url(r'^docs/facebookFriendsAction/$',
views_docs.facebook_friends_action_doc_view, name='facebookFriendsActionDocs'),
url(r'^docs/friendInvitationByEmailSend/$',
views_docs.friend_invitation_by_email_send_doc_view, name='friendInvitationByEmailSendDocs'),
url(r'^docs/friendInvitationByEmailVerify/$',
views_docs.friend_invitation_by_email_verify_doc_view, name='friendInvitationByEmailVerifyDocs'),
url(r'^docs/friendInvitationByFacebookSend/$',
views_docs.friend_invitation_by_facebook_send_doc_view, name='friendInvitationByFacebookSendDocs'),
url(r'^docs/friendInvitationByFacebookVerify/$',
views_docs.friend_invitation_by_facebook_verify_doc_view, name='friendInvitationByFacebookVerifyDocs'),
url(r'^docs/friendInvitationByWeVoteIdSend/$',
views_docs.friend_invitation_by_we_vote_id_send_doc_view, name='friendInvitationByWeVoteIdSendDocs'),
url(r'^docs/friendInviteResponse/$', views_docs.friend_invite_response_doc_view, name='friendInviteResponseDocs'),
url(r'^docs/friendList/$', views_docs.friend_list_doc_view, name='friendListDocs'),
url(r'^docs/issueFollow/$', views_docs.issue_follow_doc_view, name='issueFollowDocs'),
url(r'^docs/issuesRetrieve/$', views_docs.issues_retrieve_doc_view, name='issuesRetrieveDocs'),
url(r'^docs/issuesSyncOut/$', views_docs.issues_sync_out_doc_view, name='issuesSyncOutDocs'),
url(r'^docs/issuesLinkedToOrganization/', views_docs.issues_linked_to_organization_doc_view,
name='issuesLinkedToOrganizationDocs'),
url(r'^docs/issuesToLinkToForOrganization/', views_docs.issues_to_link_to_for_organization_doc_view,
name='issuesToLinkToForOrganizationDocs'),
url(r'^docs/measureRetrieve/$', views_docs.measure_retrieve_doc_view, name='measureRetrieveDocs'),
url(r'^docs/measuresSyncOut/$', views_docs.measures_sync_out_doc_view, name='measuresSyncOutDocs'),
url(r'^docs/officeRetrieve/$', views_docs.office_retrieve_doc_view, name='officeRetrieveDocs'),
url(r'^docs/officeSyncOut/$', views_docs.offices_sync_out_doc_view, name='officesSyncOutDocs'),
url(r'^docs/organizationCount/$', views_docs.organization_count_doc_view, name='organizationCountDocs'),
url(r'^docs/organizationFollow/', views_docs.organization_follow_doc_view, name='organizationFollowDocs'),
url(r'^docs/organizationFollowIgnore/',
views_docs.organization_follow_ignore_doc_view, name='organizationFollowIgnoreDocs'),
url(r'^docs/organizationLinkToIssueSyncOut/$',
views_docs.organization_link_to_issue_sync_out_doc_view, name='organizationLinkToIssueSyncOutDocs'),
url(r'^docs/organizationLinkToIssue/', views_docs.organization_link_to_issue_doc_view,
name='organizationLinkToIssueDocs'),
url(r'^docs/organizationRetrieve/$', views_docs.organization_retrieve_doc_view, name='organizationRetrieveDocs'),
url(r'^docs/organizationSave/$', views_docs.organization_save_doc_view, name='organizationSaveDocs'),
url(r'^docs/organizationSearch/$', views_docs.organization_search_doc_view, name='organizationSearchDocs'),
url(r'^docs/organizationsSyncOut/$', views_docs.organizations_sync_out_doc_view, name='organizationsSyncOutDocs'),
url(r'^docs/organizationStopFollowing/',
views_docs.organization_stop_following_doc_view, name='organizationStopFollowingDocs'),
url(r'^docs/organizationsFollowedRetrieve/',
views_docs.organizations_followed_retrieve_doc_view, name='organizationsFollowedRetrieveDocs'),
url(r'^docs/organizationSuggestionTasks/',
views_docs.organization_suggestion_tasks_doc_view, name='organizationSuggestionTasksDocs'),
url(r'^docs/pledgeToVoteWithVoterGuide/$',
views_docs.pledge_to_vote_with_voter_guide_doc_view, name='pledgeToVoteWithVoterGuideDocs'),
url(r'^docs/politiciansSyncOut/$', views_docs.politicians_sync_out_doc_view, name='politiciansSyncOutDocs'),
url(r'^docs/pollingLocationsSyncOut/$',
views_docs.polling_locations_sync_out_doc_view, name='pollingLocationsSyncOutDocs'),
url(r'^docs/positionLikeCount/$', views_docs.position_like_count_doc_view, name='positionLikeCountDocs'),
url(r'^docs/positionListForBallotItem/',
views_docs.position_list_for_ballot_item_doc_view, name='positionListForBallotItemDocs'),
url(r'^docs/positionListForOpinionMaker/',
views_docs.position_list_for_opinion_maker_doc_view, name='positionListForOpinionMakerDocs'),
url(r'^docs/positionListForVoter/',
views_docs.position_list_for_voter_doc_view, name='positionListForVoterDocs'),
url(r'^docs/positionOpposeCountForBallotItem/',
views_docs.position_oppose_count_for_ballot_item_doc_view, name='positionOpposeCountForBallotItemDocs'),
url(r'^docs/positionPublicOpposeCountForBallotItem/',
views_docs.position_public_oppose_count_for_ballot_item_doc_view,
name='positionPublicOpposeCountForBallotItemDocs'),
url(r'^docs/positionPublicSupportCountForBallotItem/',
views_docs.position_public_support_count_for_ballot_item_doc_view,
name='positionPublicSupportCountForBallotItemDocs'),
url(r'^docs/positionRetrieve/$', views_docs.position_retrieve_doc_view, name='positionRetrieveDocs'),
url(r'^docs/positionSave/$', views_docs.position_save_doc_view, name='positionSaveDocs'),
url(r'^docs/positionsCountForAllBallotItemsDocs/$',
views_docs.positions_count_for_all_ballot_items_doc_view, name='positionsCountForAllBallotItemsDocs'),
url(r'^docs/positionsCountForOneBallotItemDocs/$',
views_docs.positions_count_for_one_ballot_item_doc_view, name='positionsCountForOneBallotItemDocs'),
url(r'^docs/positionsSyncOut/$', views_docs.positions_sync_out_doc_view, name='positionsSyncOutDocs'),
url(r'^docs/positionSupportCountForBallotItem/',
views_docs.position_support_count_for_ballot_item_doc_view, name='positionSupportCountForBallotItemDocs'),
url(r'^docs/quickInfoRetrieve/$', views_docs.quick_info_retrieve_doc_view, name='quickInfoRetrieveDocs'),
url(r'^docs/retrieveIssuesToFollow/', views_docs.retrieve_issues_to_follow_doc_view,
name='retrieveIssuesToFollowDocs'),
url(r'^docs/saveAnalyticsAction/$',
views_docs.save_analytics_action_doc_view, name='saveAnalyticsActionDocs'),
url(r'^docs/searchAll/$',
views_docs.search_all_doc_view, name='searchAllDocs'),
url(r'^docs/twitterIdentityRetrieve/$',
views_docs.twitter_identity_retrieve_doc_view, name='twitterIdentityRetrieveDocs'),
url(r'^docs/twitterSignInRequestAccessToken/$',
views_docs.twitter_sign_in_request_access_token_doc_view, name='twitterSignInRequestAccessTokenDocs'),
url(r'^docs/twitterSignInRequestVoterInfo/$',
views_docs.twitter_sign_in_request_voter_info_doc_view, name='twitterSignInRequestVoterInfoDocs'),
url(r'^docs/twitterSignInRetrieve/$',
views_docs.twitter_sign_in_retrieve_doc_view, name='twitterSignInRetrieveDocs'),
url(r'^docs/twitterSignInStart/$', views_docs.twitter_sign_in_start_doc_view, name='twitterSignInStartDocs'),
url(r'^docs/twitterRetrieveIdsIFollow/$',
views_docs.twitter_retrieve_ids_i_follow_doc_view, name='twitterRetrieveIdsIFollowDocs'),
url(r'^docs/voterAddressRetrieve/$', views_docs.voter_address_retrieve_doc_view, name='voterAddressRetrieveDocs'),
url(r'^docs/voterAddressSave/$', views_docs.voter_address_save_doc_view, name='voterAddressSaveDocs'),
url(r'^docs/voterAllPositionsRetrieve/$',
views_docs.voter_all_positions_retrieve_doc_view, name='voterAllPositionsRetrieveDocs'),
url(r'^docs/voterAllBookmarksStatusRetrieve/$',
views_docs.voter_all_bookmarks_status_retrieve_doc_view, name='voterAllBookmarksStatusRetrieveDocs'),
url(r'^docs/voterBallotItemsRetrieve/$',
views_docs.voter_ballot_items_retrieve_doc_view, name='voterBallotItemsRetrieveDocs'),
url(r'^docs/voterBallotItemsRetrieveFromGoogleCivic/$',
views_docs.voter_ballot_items_retrieve_from_google_civic_doc_view,
name='voterBallotItemsRetrieveFromGoogleCivicDocs'),
url(r'^docs/voterBallotListRetrieve/$', views_docs.voter_ballot_list_retrieve_doc_view,
name='voterBallotListRetrieveDocs'),
url(r'^docs/voterBookmarkOffSave/$', views_docs.voter_bookmark_off_save_doc_view, name='voterBookmarkOffSaveDocs'),
url(r'^docs/voterBookmarkOnSave/$', views_docs.voter_bookmark_on_save_doc_view, name='voterBookmarkOnSaveDocs'),
url(r'^docs/voterBookmarkStatusRetrieve/$',
views_docs.voter_bookmark_status_retrieve_doc_view, name='voterBookmarkStatusRetrieveDocs'),
url(r'^docs/voterCount/$', views_docs.voter_count_doc_view, name='voterCountDocs'),
url(r'^docs/voterCreate/$', views_docs.voter_create_doc_view, name='voterCreateDocs'),
url(r'^docs/voterEmailAddressRetrieve/$',
views_docs.voter_email_address_retrieve_doc_view, name='voterEmailAddressRetrieveDocs'),
url(r'^docs/voterEmailAddressSave/$',
views_docs.voter_email_address_save_doc_view, name='voterEmailAddressSaveDocs'),
url(r'^docs/voterEmailAddressSignIn/$',
views_docs.voter_email_address_sign_in_doc_view, name='voterEmailAddressSignInDocs'),
url(r'^docs/voterEmailAddressVerify/$',
views_docs.voter_email_address_verify_doc_view, name='voterEmailAddressVerifyDocs'),
url(r'^docs/voterFacebookSaveToCurrentAccount/$',
views_docs.voter_facebook_save_to_current_account_doc_view, name='voterFacebookSaveToCurrentAccountDocs'),
url(r'^docs/voterFacebookSignInRetrieve/$',
views_docs.voter_facebook_sign_in_retrieve_doc_view, name='voterFacebookSignInRetrieveDocs'),
url(r'^docs/voterFacebookSignInSave/$',
views_docs.voter_facebook_sign_in_save_doc_view, name='voterFacebookSignInSaveDocs'),
url(r'^docs/voterFollowAllOrganizationsFollowedByOrganization/$',
views_docs.voter_follow_all_organizations_followed_by_organization_doc_view,
name='voterFollowAllOrganizationsFollowedByOrganizationDocs'),
url(r'^docs/voterGuidePossibilityRetrieve/$',
views_docs.voter_guide_possibility_retrieve_doc_view, name='voterGuidePossibilityRetrieveDocs'),
url(r'^docs/voterGuidePossibilitySave/$',
views_docs.voter_guide_possibility_save_doc_view, name='voterGuidePossibilitySaveDocs'),
url(r'^docs/voterGuidesFollowedRetrieve/$',
views_docs.voter_guides_followed_retrieve_doc_view, name='voterGuidesFollowedRetrieveDocs'),
url(r'^docs/voterGuidesFollowedByOrganizationRetrieve/$',
views_docs.voter_guides_followed_by_organization_retrieve_doc_view,
name='voterGuidesFollowedByOrganizationRetrieveDocs'),
url(r'^docs/voterGuideFollowersRetrieve/$',
views_docs.voter_guide_followers_retrieve_doc_view, name='voterGuideFollowersRetrieveDocs'),
url(r'^docs/voterGuideSave/$',
views_docs.voter_guide_save_doc_view, name='voterGuideSaveDocs'),
url(r'^docs/voterGuidesIgnoredRetrieve/$',
views_docs.voter_guides_ignored_retrieve_doc_view, name='voterGuidesIgnoredRetrieveDocs'),
url(r'^docs/voterGuidesRetrieve/$',
views_docs.voter_guides_retrieve_doc_view, name='voterGuidesRetrieveDocs'),
url(r'^docs/voterGuidesSyncOut/$', views_docs.voter_guides_sync_out_doc_view, name='voterGuidesSyncOutDocs'),
url(r'^docs/voterGuidesToFollowRetrieve/$',
views_docs.voter_guides_to_follow_retrieve_doc_view, name='voterGuidesToFollowRetrieveDocs'),
url(r'^docs/voterGuidesUpcomingRetrieve/$',
views_docs.voter_guides_upcoming_retrieve_doc_view, name='voterGuidesUpcomingRetrieveDocs'),
url(r'^docs/voterLocationRetrieveFromIP/$',
views_docs.voter_location_retrieve_from_ip_doc_view, name='voterLocationRetrieveFromIPDocs'),
url(r'^docs/voterMergeTwoAccounts/$',
views_docs.voter_merge_two_accounts_doc_view, name='voterMergeTwoAccountsDocs'),
url(r'^docs/voterPhotoSave/$', views_docs.voter_photo_save_doc_view, name='voterPhotoSaveDocs'),
url(r'^docs/voterOpposingSave/$', views_docs.voter_opposing_save_doc_view, name='voterOpposingSaveDocs'),
url(r'^docs/voterPositionRetrieve/$',
views_docs.voter_position_retrieve_doc_view, name='voterPositionRetrieveDocs'),
url(r'^docs/voterPositionCommentSave/$',
views_docs.voter_position_comment_save_doc_view, name='voterPositionCommentSaveDocs'),
url(r'^docs/voterPositionLikeOffSave/$',
views_docs.voter_position_like_off_save_doc_view, name='voterPositionLikeOffSaveDocs'),
url(r'^docs/voterPositionLikeOnSave/$',
views_docs.voter_position_like_on_save_doc_view, name='voterPositionLikeOnSaveDocs'),
url(r'^docs/voterPositionLikeStatusRetrieve/$',
views_docs.voter_position_like_status_retrieve_doc_view, name='voterPositionLikeStatusRetrieveDocs'),
url(r'^docs/voterPositionVisibilitySave/$',
views_docs.voter_position_visibility_save_doc_view, name='voterPositionVisibilitySaveDocs'),
url(r'^docs/voterRetrieve/$', views_docs.voter_retrieve_doc_view, name='voterRetrieveDocs'),
url(r'^docs/voterSignOut/$', views_docs.voter_sign_out_doc_view, name='voterSignOutDocs'),
url(r'^docs/voterSplitIntoTwoAccounts/$',
views_docs.voter_split_into_two_accounts_doc_view, name='voterSplitIntoTwoAccountsDocs'),
url(r'^docs/voterStopOpposingSave/$',
views_docs.voter_stop_opposing_save_doc_view, name='voterStopOpposingSaveDocs'),
url(r'^docs/voterStopSupportingSave/$',
views_docs.voter_stop_supporting_save_doc_view, name='voterStopSupportingSaveDocs'),
url(r'^docs/voterSupportingSave/$', views_docs.voter_supporting_save_doc_view, name='voterSupportingSaveDocs'),
url(r'^docs/voterTwitterSaveToCurrentAccount/$',
views_docs.voter_twitter_save_to_current_account_doc_view, name='voterTwitterSaveToCurrentAccountDocs'),
url(r'^docs/voterUpdate/$', views_docs.voter_update_doc_view, name='voterUpdateDocs'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/urls.py",
"copies": "1",
"size": "31965",
"license": "mit",
"hash": 6519527933093854000,
"line_mean": 76.9634146341,
"line_max": 120,
"alpha_frac": 0.7579852964,
"autogenerated": false,
"ratio": 3.401979565772669,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.4659964862172669,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views_docs.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .documentation_source import ballot_item_options_retrieve_doc, ballot_item_retrieve_doc, \
ballot_items_sync_out_doc, ballot_returned_sync_out_doc, \
candidate_retrieve_doc, \
candidates_retrieve_doc, candidates_sync_out_doc, device_id_generate_doc, \
elections_sync_out_doc, facebook_disconnect_doc, facebook_sign_in_doc, \
measure_retrieve_doc, measures_sync_out_doc, \
office_retrieve_doc, offices_sync_out_doc, \
organization_count_doc, organizations_followed_retrieve_doc, \
organization_follow_doc, organization_follow_ignore_doc, organization_stop_following_doc, \
organization_retrieve_doc, organization_save_doc, organization_search_doc, organizations_sync_out_doc, \
polling_locations_sync_out_doc, \
position_like_count_doc, position_list_for_ballot_item_doc, position_list_for_opinion_maker_doc, \
position_oppose_count_for_ballot_item_doc, \
position_public_oppose_count_for_ballot_item_doc, position_retrieve_doc, position_save_doc, \
positions_sync_out_doc, \
position_public_support_count_for_ballot_item_doc, position_support_count_for_ballot_item_doc, \
positions_count_for_all_ballot_items_doc, positions_count_for_one_ballot_item_doc, \
quick_info_retrieve_doc, search_all_doc, twitter_identity_retrieve_doc, \
twitter_sign_in_start_doc, twitter_sign_in_request_access_token_doc, twitter_sign_in_request_voter_info_doc, \
voter_address_retrieve_doc, \
voter_address_save_doc, voter_all_positions_retrieve_doc, voter_all_stars_status_retrieve_doc, \
voter_ballot_items_retrieve_doc, voter_ballot_items_retrieve_from_google_civic_doc, voter_count_doc, \
voter_create_doc, voter_guide_possibility_retrieve_doc, voter_guide_possibility_save_doc, \
voter_guides_followed_retrieve_doc, voter_guides_sync_out_doc, voter_guides_to_follow_retrieve_doc, \
voter_location_retrieve_from_ip_doc, voter_photo_save_doc, \
voter_position_like_off_save_doc, voter_position_like_on_save_doc, voter_position_like_status_retrieve_doc, \
voter_position_comment_save_doc, voter_position_retrieve_doc, voter_position_visibility_save_doc, \
voter_opposing_save_doc, voter_retrieve_doc, voter_sign_out_doc, voter_star_off_save_doc, voter_star_on_save_doc, \
voter_star_status_retrieve_doc, voter_stop_opposing_save_doc, \
voter_stop_supporting_save_doc, voter_supporting_save_doc, voter_update_doc
from config.base import get_environment_variable
from django.contrib.messages import get_messages
from django.shortcuts import render
from voter.models import voter_setup
from wevote_functions.functions import get_voter_api_device_id, set_voter_api_device_id, positive_value_exists
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def apis_index_doc_view(request):
"""
Show a list of available APIs
"""
# Create a voter_device_id and voter in the database if one doesn't exist yet
results = voter_setup(request)
voter_api_device_id = results['voter_api_device_id']
store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']
messages_on_stage = get_messages(request)
template_values = {
'next': next,
'messages_on_stage': messages_on_stage,
}
response = render(request, 'apis_v1/apis_index.html', template_values)
# We want to store the voter_device_id cookie if it is new
if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
set_voter_api_device_id(request, response, voter_api_device_id)
return response
def ballot_item_options_retrieve_doc_view(request):
"""
Show documentation about ballotItemOptionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_options_retrieve_doc.ballot_item_options_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_item_retrieve_doc_view(request):
"""
Show documentation about ballotItemRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_retrieve_doc.ballot_item_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_items_sync_out_doc_view(request):
"""
Show documentation about ballotItemsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_items_sync_out_doc.ballot_items_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_returned_sync_out_doc_view(request):
"""
Show documentation about ballotReturnedSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_returned_sync_out_doc.ballot_returned_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidate_retrieve_doc_view(request):
"""
Show documentation about candidateRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidate_retrieve_doc.candidate_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_retrieve_doc.candidates_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_sync_out_doc_view(request):
"""
Show documentation about candidatesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_sync_out_doc.candidates_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def device_id_generate_doc_view(request):
"""
Show documentation about deviceIdGenerate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = device_id_generate_doc.device_id_generate_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def elections_sync_out_doc_view(request):
"""
Show documentation about electionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = elections_sync_out_doc.elections_sync_out_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_disconnect_doc_view(request):
"""
Show documentation about facebookDisconnect
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_disconnect_doc.facebook_disconnect_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_sign_in_doc_view(request):
"""
Show documentation about facebookSignIn
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_sign_in_doc.facebook_sign_in_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measure_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measure_retrieve_doc.measure_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measures_sync_out_doc_view(request):
"""
Show documentation about measuresSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measures_sync_out_doc.measures_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def office_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = office_retrieve_doc.office_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def offices_sync_out_doc_view(request):
"""
Show documentation about officesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = offices_sync_out_doc.offices_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_count_doc_view(request):
"""
Show documentation about organizationCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_count_doc.organization_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_doc_view(request):
"""
Show documentation about organizationFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_doc.organization_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_followed_retrieve_doc.organizations_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_ignore_doc_view(request):
"""
Show documentation about organizationFollowIgnore
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_ignore_doc.organization_follow_ignore_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_stop_following_doc_view(request):
"""
Show documentation about organizationStopFollowing
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_stop_following_doc.organization_stop_following_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_retrieve_doc_view(request):
"""
Show documentation about organizationRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_retrieve_doc.organization_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_save_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_save_doc.organization_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_search_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_search_doc.organization_search_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_sync_out_doc_view(request):
"""
Show documentation about organizationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_sync_out_doc.organizations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_ballot_item_doc_view(request):
"""
Show documentation about positionListForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_ballot_item_doc.position_list_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_opinion_maker_doc_view(request):
"""
Show documentation about positionListForOpinionMaker
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_opinion_maker_doc.position_list_for_opinion_maker_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_retrieve_doc_view(request):
"""
Show documentation about positionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_retrieve_doc.position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_save_doc_view(request):
"""
Show documentation about positionSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_save_doc.position_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_oppose_count_for_ballot_item_doc.\
position_oppose_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_support_count_for_ballot_item_doc.\
position_support_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_oppose_count_for_ballot_item_doc.\
position_public_oppose_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_support_count_for_ballot_item_doc.\
position_public_support_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_all_ballot_items_doc_view(request):
"""
Show documentation about positionsCountForAllBallotItems
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_all_ballot_items_doc.positions_count_for_all_ballot_items_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_one_ballot_item_doc_view(request):
"""
Show documentation about positionsCountForOneBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def quick_info_retrieve_doc_view(request):
"""
Show documentation about quickInfoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = quick_info_retrieve_doc.\
quick_info_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def search_all_doc_view(request):
"""
Show documentation about searchAll
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = search_all_doc.\
search_all_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_identity_retrieve_doc_view(request):
"""
Show documentation about twitterIdentityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_identity_retrieve_doc.twitter_identity_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_start_doc_view(request):
"""
Show documentation about twitterSignInStart
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_sign_in_start_doc.twitter_sign_in_start_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_access_token_doc_view(request):
"""
Show documentation about twitterSignInRequestAccessToken
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_access_token_doc.twitter_sign_in_request_access_token_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_voter_info_doc_view(request):
"""
Show documentation about twitterSignInRequestVoterInfo
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_voter_info_doc.twitter_sign_in_request_voter_info_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_retrieve_doc_view(request):
"""
Show documentation about voterAddressRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_retrieve_doc.voter_address_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_save_doc_view(request):
"""
Show documentation about voterSaveRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_save_doc.voter_address_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_doc.voter_ballot_items_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_from_google_civic_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieveFromGoogleCivic
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_from_google_civic_doc.\
voter_ballot_items_retrieve_from_google_civic_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_count_doc_view(request):
"""
Show documentation about voterCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_count_doc.voter_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_create_doc_view(request):
"""
Show documentation about voterCreate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_create_doc.voter_create_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_retrieve_doc_view(request):
"""
Show documentation about voterGuidePossibilityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_retrieve_doc.voter_guide_possibility_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_save_doc_view(request):
"""
Show documentation about voterGuidePossibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_possibility_save_doc.voter_guide_possibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_followed_retrieve_doc.voter_guides_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_sync_out_doc_view(request):
"""
Show documentation about voterGuidesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_sync_out_doc.voter_guides_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_to_follow_retrieve_doc_view(request):
"""
Show documentation about voterGuidesToFollowRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_to_follow_retrieve_doc.voter_guides_to_follow_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_location_retrieve_from_ip_doc_view(request):
"""
Show documentation about voterLocationRetrieveFromIP
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_location_retrieve_from_ip_doc.voter_location_retrieve_from_ip_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_photo_save_doc_view(request):
"""
Show documentation about voterPhotoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_photo_save_doc.voter_photo_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_off_save_doc_view(request):
"""
Show documentation about voterPositionLikeOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_off_save_doc.voter_position_like_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_on_save_doc_view(request):
"""
Show documentation about voterPositionLikeOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_on_save_doc.voter_position_like_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_status_retrieve_doc_view(request):
"""
Show documentation about voterPositionLikeStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_status_retrieve_doc.voter_position_like_status_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def polling_locations_sync_out_doc_view(request):
"""
Show documentation about pollingLocationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = polling_locations_sync_out_doc.polling_locations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_like_count_doc_view(request):
"""
Show documentation about positionLikeCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_like_count_doc.position_like_count_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_positions_retrieve_doc_view(request):
"""
Show documentation about voterAllPositionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_positions_retrieve_doc.voter_all_positions_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_stars_status_retrieve_doc_view(request):
"""
Show documentation about voterAllStarsStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_stars_status_retrieve_doc.voter_all_stars_status_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_retrieve_doc_view(request):
"""
Show documentation about voterPositionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_retrieve_doc.voter_position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_comment_save_doc_view(request):
"""
Show documentation about voterPositionCommentSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_comment_save_doc.voter_position_comment_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_visibility_save_doc_view(request):
"""
Show documentation about voterPositionVisibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_visibility_save_doc.voter_position_visibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_opposing_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_opposing_save_doc.voter_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_opposing_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_retrieve_doc_view(request):
"""
Show documentation about voterRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_retrieve_doc.voter_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_supporting_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_supporting_save_doc.voter_stop_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_supporting_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_supporting_save_doc.voter_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_sign_out_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_sign_out_doc.voter_sign_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_star_off_save_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_star_off_save_doc.voter_star_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_star_on_save_doc_view(request):
"""
Show documentation about voterStarOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_star_on_save_doc.voter_star_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_star_status_retrieve_doc_view(request):
"""
Show documentation about voterStarStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_star_status_retrieve_doc.voter_star_status_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_update_doc_view(request):
"""
Show documentation about voterUpdate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_update_doc.voter_update_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
| {
"repo_name": "wevote/WebAppPublic",
"path": "apis_v1/views_docs.py",
"copies": "1",
"size": "33469",
"license": "bsd-3-clause",
"hash": -3199976514379304000,
"line_mean": 40.3197530864,
"line_max": 120,
"alpha_frac": 0.7254773074,
"autogenerated": false,
"ratio": 3.1470615890926186,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4372538896492618,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_activity.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
from django.http import HttpResponse
import json
import threading
import time
from activity.controllers import update_or_create_activity_notice_seed_for_activity_posts
from activity.models import ActivityManager, NOTICE_FRIEND_ACTIVITY_POSTS, NOTICE_FRIEND_ENDORSEMENTS, \
NOTICE_FRIEND_ENDORSEMENTS_SEED
from config.base import get_environment_variable
from friend.models import FriendManager
from google_firebase_api.cloud_messaging import send_single_message
from twitter.models import TwitterUserManager
from voter.models import fetch_voter_we_vote_id_from_voter_device_link, VoterManager, VoterDeviceLinkManager, \
VoterDeviceLink
from wevote_functions.functions import get_voter_device_id, positive_value_exists, wevote_functions
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def activity_comment_save_view(request): # activityCommentSave
"""
Save comment about an existing ActivityPost or other parent item.
:param request:
:return:
"""
status = ''
activity_manager = ActivityManager()
activity_comment_we_vote_id = request.GET.get('activity_comment_we_vote_id', False)
parent_we_vote_id = request.GET.get('parent_we_vote_id', False)
parent_comment_we_vote_id = request.GET.get('parent_comment_we_vote_id', False)
statement_text = request.GET.get('statement_text', False)
visibility_setting = request.GET.get('visibility_setting', False)
if visibility_setting not in ['FRIENDS_ONLY', 'SHOW_PUBLIC']:
visibility_setting = 'FRIENDS_ONLY'
visibility_is_public = visibility_setting == 'SHOW_PUBLIC'
updated_values = {
'activity_comment_created': False,
'commenter_name': '',
'commenter_organization_we_vote_id': '',
'commenter_twitter_followers_count': 0,
'commenter_twitter_handle': '',
'commenter_voter_we_vote_id': '',
'commenter_profile_image_url_medium': '',
'commenter_profile_image_url_tiny': '',
'parent_we_vote_id': parent_we_vote_id,
'parent_comment_we_vote_id': parent_comment_we_vote_id,
'statement_text': statement_text,
'visibility_is_public': visibility_is_public,
}
voter_device_id = get_voter_device_id(request)
voter_manager = VoterManager()
results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id, read_only=True)
if results['voter_found']:
voter = results['voter']
commenter_twitter_followers_count = 0
if positive_value_exists(voter.linked_organization_we_vote_id):
# Is there a Twitter handle linked to this organization? If so, update the information.
twitter_user_manager = TwitterUserManager()
twitter_link_results = \
twitter_user_manager.retrieve_twitter_link_to_organization_from_organization_we_vote_id(
voter.linked_organization_we_vote_id)
if twitter_link_results['twitter_link_to_organization_found']:
twitter_link_to_organization = twitter_link_results['twitter_link_to_organization']
twitter_results = \
twitter_user_manager.retrieve_twitter_user_locally_or_remotely(
twitter_link_to_organization.twitter_id)
if twitter_results['twitter_user_found']:
twitter_user = twitter_results['twitter_user']
try:
commenter_twitter_followers_count = twitter_user.twitter_followers_count \
if positive_value_exists(twitter_user.twitter_followers_count) else 0
except Exception as e:
status += "FAILED_TO_RETRIEVE_TWITTER_FOLLOWERS_COUNT " + str(e) + ' '
updated_values['commenter_name'] = voter.get_full_name(real_name_only=True)
updated_values['commenter_voter_we_vote_id'] = voter.we_vote_id
updated_values['commenter_organization_we_vote_id'] = voter.linked_organization_we_vote_id
updated_values['commenter_profile_image_url_medium'] = voter.we_vote_hosted_profile_image_url_medium
updated_values['commenter_profile_image_url_tiny'] = voter.we_vote_hosted_profile_image_url_tiny
updated_values['commenter_twitter_followers_count'] = commenter_twitter_followers_count
updated_values['commenter_twitter_handle'] = voter.twitter_screen_name
updated_values['parent_we_vote_id'] = parent_we_vote_id
updated_values['parent_comment_we_vote_id'] = parent_comment_we_vote_id
if not positive_value_exists(updated_values['commenter_voter_we_vote_id']):
status += "ACTIVITY_COMMENT_SAVE_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = activity_manager.update_or_create_activity_comment(
activity_comment_we_vote_id=activity_comment_we_vote_id,
updated_values=updated_values,
commenter_voter_we_vote_id=updated_values['commenter_voter_we_vote_id'],
)
status += results['status']
success = results['success']
activity_comment_dict = {}
if results['activity_comment_found']:
activity_comment = results['activity_comment']
activity_comment_dict = {
'activity_comment_created': results['activity_comment_created'],
'date_created': activity_comment.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': activity_comment.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'commenter_name': activity_comment.commenter_name,
'commenter_organization_we_vote_id': activity_comment.commenter_organization_we_vote_id,
'commenter_voter_we_vote_id': activity_comment.commenter_voter_we_vote_id,
'commenter_profile_image_url_medium': activity_comment.commenter_profile_image_url_medium,
'commenter_profile_image_url_tiny': activity_comment.commenter_profile_image_url_tiny,
'commenter_twitter_handle': activity_comment.commenter_twitter_handle,
'commenter_twitter_followers_count': activity_comment.commenter_twitter_followers_count,
'parent_we_vote_id': activity_comment.parent_we_vote_id,
'parent_comment_we_vote_id': activity_comment.parent_comment_we_vote_id,
'statement_text': activity_comment.statement_text,
'visibility_is_public': activity_comment.visibility_is_public,
'we_vote_id': activity_comment.we_vote_id,
}
activity_comment_dict['status'] = status
activity_comment_dict['success'] = success
return HttpResponse(json.dumps(activity_comment_dict), content_type='application/json')
def activity_list_retrieve_view(request): # activityListRetrieve
"""
Retrieve activity so we can populate the news page
:param request:
:return:
"""
status = ''
activity_list = []
activity_manager = ActivityManager()
activity_notice_seed_list = []
activity_post_list = []
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_friend_we_vote_id_list = []
voter_we_vote_id = ''
activity_tidbit_we_vote_id_list = request.GET.getlist('activity_tidbit_we_vote_id_list[]')
activity_tidbit_we_vote_id_list = list(filter(None, activity_tidbit_we_vote_id_list))
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if not positive_value_exists(voter_we_vote_id):
status += "RETRIEVE_ACTIVITY_LIST_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
'activity_list': activity_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# Retrieve the NOTICE_FRIEND_ENDORSEMENTS_SEED and the ActivityPost entries below
results = activity_manager.retrieve_activity_notice_seed_list_for_recipient(
recipient_voter_we_vote_id=voter_we_vote_id,
kind_of_seed_list=[NOTICE_FRIEND_ENDORSEMENTS_SEED],
limit_to_activity_tidbit_we_vote_id_list=activity_tidbit_we_vote_id_list)
if results['success']:
activity_notice_seed_list = results['activity_notice_seed_list']
voter_friend_we_vote_id_list = results['voter_friend_we_vote_id_list']
else:
status += results['status']
status += "RETRIEVE_ACTIVITY_LIST_FAILED "
for activity_notice_seed in activity_notice_seed_list:
new_positions_entered_count = 0
position_name_list = []
position_we_vote_id_list = []
# In this scenario we want to return both friends and public values
# Position names
if positive_value_exists(activity_notice_seed.position_names_for_friends_serialized):
position_name_list += json.loads(activity_notice_seed.position_names_for_friends_serialized)
if positive_value_exists(activity_notice_seed.position_names_for_public_serialized):
position_name_list += json.loads(activity_notice_seed.position_names_for_public_serialized)
# Position we_vote_ids
if positive_value_exists(activity_notice_seed.position_we_vote_ids_for_friends_serialized):
position_we_vote_id_list += json.loads(activity_notice_seed.position_we_vote_ids_for_friends_serialized)
if positive_value_exists(activity_notice_seed.position_we_vote_ids_for_public_serialized):
position_we_vote_id_list += json.loads(activity_notice_seed.position_we_vote_ids_for_public_serialized)
new_positions_entered_count += len(position_we_vote_id_list)
if not positive_value_exists(activity_notice_seed.we_vote_id):
try:
activity_notice_seed.save()
except Exception as e:
status += "COULD_NOT_UPDATE_SEED_WE_VOTE_ID: " + str(e) + ' '
activity_notice_seed_dict = {
'date_created': activity_notice_seed.date_of_notice.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': activity_notice_seed.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'date_of_notice': activity_notice_seed.date_of_notice.strftime('%Y-%m-%d %H:%M:%S'),
'id': activity_notice_seed.id, # We normalize to generate activityTidbitKey
'activity_notice_seed_id': activity_notice_seed.id,
'kind_of_activity': "ACTIVITY_NOTICE_SEED",
'kind_of_seed': activity_notice_seed.kind_of_seed,
'new_positions_entered_count': new_positions_entered_count,
'position_name_list': position_name_list,
'position_we_vote_id_list': position_we_vote_id_list,
'speaker_name': activity_notice_seed.speaker_name,
'speaker_organization_we_vote_id': activity_notice_seed.speaker_organization_we_vote_id,
'speaker_voter_we_vote_id': activity_notice_seed.speaker_voter_we_vote_id,
'speaker_profile_image_url_medium': activity_notice_seed.speaker_profile_image_url_medium,
'speaker_profile_image_url_tiny': activity_notice_seed.speaker_profile_image_url_tiny,
'speaker_twitter_handle': activity_notice_seed.speaker_twitter_handle,
'speaker_twitter_followers_count': activity_notice_seed.speaker_twitter_followers_count,
'we_vote_id': activity_notice_seed.we_vote_id,
}
activity_list.append(activity_notice_seed_dict)
# ####################################################
# Retrieve entries directly in the ActivityPost table
results = activity_manager.retrieve_activity_post_list_for_recipient(
recipient_voter_we_vote_id=voter_we_vote_id,
limit_to_activity_tidbit_we_vote_id_list=activity_tidbit_we_vote_id_list,
voter_friend_we_vote_id_list=voter_friend_we_vote_id_list)
if results['success']:
activity_post_list = results['activity_post_list']
else:
status += results['status']
status += "RETRIEVE_ACTIVITY_POST_LIST_FAILED "
for activity_post in activity_post_list:
date_created_string = ''
if activity_post.date_created:
date_created_string = activity_post.date_created.strftime('%Y-%m-%d %H:%M:%S')
if not positive_value_exists(activity_post.we_vote_id):
try:
activity_post.save()
except Exception as e:
status += "COULD_NOT_UPDATE_POST_WE_VOTE_ID: " + str(e) + ' '
activity_post_dict = {
'date_created': date_created_string,
'date_last_changed': activity_post.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'date_of_notice': date_created_string,
'id': activity_post.id, # We normalize to generate activityTidbitKey
'activity_post_id': activity_post.id,
'kind_of_activity': 'ACTIVITY_POST',
'kind_of_seed': '',
'new_positions_entered_count': 0,
'position_name_list': [],
'position_we_vote_id_list': [],
'speaker_name': activity_post.speaker_name,
'speaker_organization_we_vote_id': activity_post.speaker_organization_we_vote_id,
'speaker_voter_we_vote_id': activity_post.speaker_voter_we_vote_id,
'speaker_profile_image_url_medium': activity_post.speaker_profile_image_url_medium,
'speaker_profile_image_url_tiny': activity_post.speaker_profile_image_url_tiny,
'speaker_twitter_handle': activity_post.speaker_twitter_handle,
'speaker_twitter_followers_count': activity_post.speaker_twitter_followers_count,
'statement_text': activity_post.statement_text,
'visibility_is_public': activity_post.visibility_is_public,
'we_vote_id': activity_post.we_vote_id,
}
activity_list.append(activity_post_dict)
# Now cycle through these activities and retrieve all related comments
activity_list_with_comments = []
for activity_tidbit_dict in activity_list:
results = activity_manager.retrieve_activity_comment_list(
parent_we_vote_id=activity_tidbit_dict['we_vote_id'])
activity_comment_list = []
if results['success']:
activity_comment_object_list = results['activity_comment_list']
for activity_comment in activity_comment_object_list:
# Retrieve the Child comments
child_results = activity_manager.retrieve_activity_comment_list(
parent_comment_we_vote_id=activity_comment.we_vote_id)
child_comment_list = []
if results['success']:
child_comment_object_list = child_results['activity_comment_list']
for child_comment in child_comment_object_list:
child_comment_dict = {
'date_created': child_comment.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': child_comment.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'commenter_name': child_comment.commenter_name,
'commenter_organization_we_vote_id': child_comment.commenter_organization_we_vote_id,
'commenter_voter_we_vote_id': child_comment.commenter_voter_we_vote_id,
'commenter_profile_image_url_medium': child_comment.commenter_profile_image_url_medium,
'commenter_profile_image_url_tiny': child_comment.commenter_profile_image_url_tiny,
'commenter_twitter_handle': child_comment.commenter_twitter_handle,
'commenter_twitter_followers_count': child_comment.commenter_twitter_followers_count,
'parent_we_vote_id': child_comment.parent_we_vote_id,
'parent_comment_we_vote_id': child_comment.parent_comment_we_vote_id,
'statement_text': child_comment.statement_text,
'visibility_is_public': child_comment.visibility_is_public,
'we_vote_id': child_comment.we_vote_id,
}
child_comment_list.append(child_comment_dict)
activity_comment_dict = {
'comment_list': child_comment_list,
'date_created': activity_comment.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': activity_comment.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'commenter_name': activity_comment.commenter_name,
'commenter_organization_we_vote_id': activity_comment.commenter_organization_we_vote_id,
'commenter_voter_we_vote_id': activity_comment.commenter_voter_we_vote_id,
'commenter_profile_image_url_medium': activity_comment.commenter_profile_image_url_medium,
'commenter_profile_image_url_tiny': activity_comment.commenter_profile_image_url_tiny,
'commenter_twitter_handle': activity_comment.commenter_twitter_handle,
'commenter_twitter_followers_count': activity_comment.commenter_twitter_followers_count,
'parent_we_vote_id': activity_comment.parent_we_vote_id,
'parent_comment_we_vote_id': activity_comment.parent_comment_we_vote_id,
'statement_text': activity_comment.statement_text,
'visibility_is_public': activity_comment.visibility_is_public,
'we_vote_id': activity_comment.we_vote_id,
}
activity_comment_list.append(activity_comment_dict)
activity_tidbit_dict['activity_comment_list'] = activity_comment_list
activity_list_with_comments.append(activity_tidbit_dict)
# Order entries in the activity_list by "date_created"
from operator import itemgetter
activity_list_ordered = sorted(activity_list_with_comments, key=itemgetter('date_created'), reverse=True)
json_data = {
'status': status,
'success': True,
'activity_list': activity_list_ordered,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def activity_notice_list_retrieve_view(request): # activityNoticeListRetrieve
"""
Retrieve activity notices so we can show the voter recent activity
:param request:
:return:
"""
status = ''
activity_notice_list = []
activity_manager = ActivityManager()
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if not positive_value_exists(voter_we_vote_id):
status += "RETRIEVE_ACTIVITY_NOTICE_LIST_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
'activity_notice_list': activity_notice_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
activity_notice_id_list_clicked = request.GET.getlist('activity_notice_id_list_clicked[]')
activity_notice_id_list_seen = request.GET.getlist('activity_notice_id_list_seen[]')
if activity_notice_id_list_clicked and len(activity_notice_id_list_clicked):
results = activity_manager.update_activity_notice_list_in_bulk(
recipient_voter_we_vote_id=voter_we_vote_id,
activity_notice_id_list=activity_notice_id_list_clicked,
activity_notice_clicked=True
)
status += results['status']
if activity_notice_id_list_seen and len(activity_notice_id_list_seen):
results = activity_manager.update_activity_notice_list_in_bulk(
recipient_voter_we_vote_id=voter_we_vote_id,
activity_notice_id_list=activity_notice_id_list_seen,
activity_notice_seen=True,
)
status += results['status']
results = activity_manager.retrieve_activity_notice_list_for_recipient(recipient_voter_we_vote_id=voter_we_vote_id)
if not results['success']:
status += results['status']
status += "RETRIEVE_ACTIVITY_NOTICE_LIST_FAILED "
json_data = {
'status': status,
'success': False,
'activity_notice_list': activity_notice_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
modified_activity_notice_list = []
activity_notice_list = results['activity_notice_list']
for activity_notice in activity_notice_list:
position_name_list = []
position_we_vote_id_list = []
include_this_activity_notice = False
new_positions_entered_count = 0
if activity_notice.kind_of_notice == NOTICE_FRIEND_ENDORSEMENTS:
if positive_value_exists(activity_notice.position_name_list_serialized):
position_name_list = json.loads(activity_notice.position_name_list_serialized)
if positive_value_exists(activity_notice.position_we_vote_id_list_serialized):
position_we_vote_id_list = json.loads(activity_notice.position_we_vote_id_list_serialized)
new_positions_entered_count = activity_notice.new_positions_entered_count
include_this_activity_notice = True
elif activity_notice.kind_of_notice == NOTICE_FRIEND_ACTIVITY_POSTS:
include_this_activity_notice = True
if include_this_activity_notice:
activity_notice_dict = {
'activity_notice_clicked': activity_notice.activity_notice_clicked,
'activity_notice_seen': activity_notice.activity_notice_seen,
'activity_tidbit_we_vote_id': activity_notice.activity_tidbit_we_vote_id,
'date_last_changed': activity_notice.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'date_of_notice': activity_notice.date_of_notice.strftime('%Y-%m-%d %H:%M:%S'),
'activity_notice_id': activity_notice.id,
'kind_of_notice': activity_notice.kind_of_notice,
'new_positions_entered_count': new_positions_entered_count,
'number_of_comments': activity_notice.number_of_comments,
'number_of_likes': activity_notice.number_of_likes,
'position_name_list': position_name_list,
'position_we_vote_id_list': position_we_vote_id_list,
'speaker_name': activity_notice.speaker_name,
'speaker_organization_we_vote_id': activity_notice.speaker_organization_we_vote_id,
'speaker_voter_we_vote_id': activity_notice.speaker_voter_we_vote_id,
'speaker_profile_image_url_medium': activity_notice.speaker_profile_image_url_medium,
'speaker_profile_image_url_tiny': activity_notice.speaker_profile_image_url_tiny,
'statement_text_preview': activity_notice.statement_text_preview,
}
modified_activity_notice_list.append(activity_notice_dict)
json_data = {
'status': status,
'success': True,
'activity_notice_list': modified_activity_notice_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def activity_post_save_view(request): # activityPostSave
"""
Save new Tidbit, or edit existing.
:param request:
:return:
"""
status = ''
activity_manager = ActivityManager()
start = time.time()
activity_post_we_vote_id = request.GET.get('activity_post_we_vote_id', False)
statement_text = request.GET.get('statement_text', False)
visibility_setting = request.GET.get('visibility_setting', False)
if visibility_setting not in ['FRIENDS_ONLY', 'SHOW_PUBLIC']:
visibility_setting = 'FRIENDS_ONLY'
visibility_is_public = visibility_setting == 'SHOW_PUBLIC'
updated_values = {
'speaker_name': '',
'speaker_organization_we_vote_id': '',
'speaker_twitter_followers_count': 0,
'speaker_twitter_handle': '',
'speaker_voter_we_vote_id': '',
'speaker_profile_image_url_medium': '',
'speaker_profile_image_url_tiny': '',
'statement_text': statement_text,
'visibility_is_public': visibility_is_public,
}
voter_device_id = get_voter_device_id(request)
voter = None
voter_found = False
voter_manager = VoterManager()
results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id, read_only=True)
if results['voter_found']:
voter = results['voter']
voter_found = True
speaker_twitter_followers_count = 0
if positive_value_exists(voter.linked_organization_we_vote_id):
# Is there a Twitter handle linked to this organization? If so, update the information.
twitter_user_manager = TwitterUserManager()
twitter_link_results = \
twitter_user_manager.retrieve_twitter_link_to_organization_from_organization_we_vote_id(
voter.linked_organization_we_vote_id)
if twitter_link_results['twitter_link_to_organization_found']:
twitter_link_to_organization = twitter_link_results['twitter_link_to_organization']
twitter_results = \
twitter_user_manager.retrieve_twitter_user_locally_or_remotely(
twitter_link_to_organization.twitter_id)
if twitter_results['twitter_user_found']:
twitter_user = twitter_results['twitter_user']
try:
speaker_twitter_followers_count = twitter_user.twitter_followers_count \
if positive_value_exists(twitter_user.twitter_followers_count) else 0
except Exception as e:
status += "FAILED_TO_RETRIEVE_TWITTER_FOLLOWERS_COUNT " + str(e) + ' '
updated_values['speaker_name'] = voter.get_full_name(real_name_only=True)
updated_values['speaker_voter_we_vote_id'] = voter.we_vote_id
updated_values['speaker_organization_we_vote_id'] = voter.linked_organization_we_vote_id
updated_values['speaker_profile_image_url_medium'] = voter.we_vote_hosted_profile_image_url_medium
updated_values['speaker_profile_image_url_tiny'] = voter.we_vote_hosted_profile_image_url_tiny
updated_values['speaker_twitter_followers_count'] = speaker_twitter_followers_count
updated_values['speaker_twitter_handle'] = voter.twitter_screen_name
if not voter_found or not positive_value_exists(updated_values['speaker_voter_we_vote_id']):
status += "ACTIVITY_TIDBIT_SAVE_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# September 19, 2020: Runs the cloud notification in a thread, so that the call to ActivityPostSave is not slowed
# down by the extra work.
# We are using the Python version of the Java threads API, but CPython is inherently single threaded -- it runs only
# one thread at a time, and switches execution between threads to simulate simultaneous execution. CPython does not
# provide the concurrent threading that you get in Java or C, where threads can be started up to run concurrently
# on other processor cores, but it does allow activity_post_save_view(request) to return quickly (in about 70ms on
# a MacBookPro), and then runs the thread (as currently loaded down with lots of temporary logging) in about 300ms
# for a single fcm notification send.
#
# (As an experiment I ran firebase_notification_send_to_cordova_apps 20 times in a loop within the thread and the
# time to execute activity_post_save_view was unchanged, but the thread took about 2 seconds to complete.)
#
# So with our load balancing setup, a Django instance would be tied up for an average of about 70ms for the
# ActivityPostSave execution, and would continue to be further tied up with the 300ms for the "notification send"
# thread to run to completion.
#
# This eliminates the need to batch process the notifications.
try:
t = threading.Thread(name='fcm_notification_send_thread', target=firebase_notification_send_to_cordova_apps,
args=(voter.we_vote_id, voter.get_full_name(real_name_only=True), statement_text))
t.start()
except Exception as e:
status += "FAILED_DURING-firebase_notification_send_to_cordova_apps " + str(e) + " "
results = activity_manager.update_or_create_activity_post(
activity_post_we_vote_id=activity_post_we_vote_id,
updated_values=updated_values,
speaker_voter_we_vote_id=updated_values['speaker_voter_we_vote_id'],
)
status += results['status']
success = results['success']
activity_post_dict = {}
if results['activity_post_found']:
activity_post = results['activity_post']
activity_results = update_or_create_activity_notice_seed_for_activity_posts(
activity_post_we_vote_id=activity_post.we_vote_id,
visibility_is_public=visibility_is_public,
speaker_name=voter.get_full_name(real_name_only=True),
speaker_organization_we_vote_id=voter.linked_organization_we_vote_id,
speaker_voter_we_vote_id=voter.we_vote_id,
speaker_profile_image_url_medium=voter.we_vote_hosted_profile_image_url_medium,
speaker_profile_image_url_tiny=voter.we_vote_hosted_profile_image_url_tiny,
statement_text=activity_post.statement_text)
status += activity_results['status']
activity_post_dict = {
'date_created': activity_post.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': activity_post.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'date_of_notice': activity_post.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'id': activity_post.id, # We normalize to generate activityTidbitKey
'activity_post_id': activity_post.id,
'kind_of_activity': 'ACTIVITY_POST',
'kind_of_seed': '',
'new_positions_entered_count': 0,
'position_we_vote_id_list': [],
'speaker_name': activity_post.speaker_name,
'speaker_organization_we_vote_id': activity_post.speaker_organization_we_vote_id,
'speaker_voter_we_vote_id': activity_post.speaker_voter_we_vote_id,
'speaker_profile_image_url_medium': activity_post.speaker_profile_image_url_medium,
'speaker_profile_image_url_tiny': activity_post.speaker_profile_image_url_tiny,
'speaker_twitter_handle': activity_post.speaker_twitter_handle,
'speaker_twitter_followers_count': activity_post.speaker_twitter_followers_count,
'statement_text': activity_post.statement_text,
'visibility_is_public': activity_post.visibility_is_public,
'we_vote_id': activity_post.we_vote_id,
}
activity_post_dict['status'] = status
activity_post_dict['success'] = success
end = str(time.time() - start)
logger.info('activity_post_save_view elapsed time = ' + end)
return HttpResponse(json.dumps(activity_post_dict), content_type='application/json')
def firebase_notification_send_to_cordova_apps(we_vote_id, speaker_name, statement_text):
"""
Send a notification to all the speaker's friends on all of their devices that they have used in the last 15 days
This makes a best effort to send the messages, with no error handling on "not found" problems
Sept 18, 2020: temporary success logging for viewing in Splunk
:param we_vote_id:
:param speaker_name:
:param statement_text:
:return:
"""
start = time.time()
friend_manager = FriendManager()
activity_manager = ActivityManager()
voter_device_link_manager = VoterDeviceLinkManager()
friend_results = friend_manager.retrieve_friends_we_vote_id_list(we_vote_id)
if friend_results['friends_we_vote_id_list_found']:
friends_we_vote_id_list = friend_results['friends_we_vote_id_list']
for recipient_voter_id in friends_we_vote_id_list:
try:
results = activity_manager.retrieve_activity_notice_list_for_recipient(
recipient_voter_we_vote_id=recipient_voter_id)
activity_notice_list = results['activity_notice_list']
badge_number = activity_notice_list.count() + 1
body = speaker_name + " posted \"" + statement_text + "\""
time_threshold = datetime.now() - timedelta(days=15)
voter_id = ''.join(filter(str.isdigit, recipient_voter_id))
voter_device_link_query = VoterDeviceLink.objects.all()
voter_device_link_query = voter_device_link_query.filter(voter_id=voter_id)
voter_device_link_query = voter_device_link_query.filter(date_last_changed__gt=time_threshold)
device_list = list(voter_device_link_query)
for device in device_list:
send_single_message(device.platform_type, device.firebase_fcm_token, "We Vote", body,
badge_number)
logger.info('firebase_notification_send_to_cordova_apps sent : ' + device.platform_type +
device.firebase_fcm_token + "We Vote" + body + str(badge_number))
except Exception as e:
logger.error('firebase_notification_send_to_cordova_apps threw: ', e)
end = str(time.time() - start)
logger.info('firebase fcm_notification_send_thread terminated after = ' + end + ' seconds.')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_activity.py",
"copies": "1",
"size": "35747",
"license": "mit",
"hash": 4284211825635188000,
"line_mean": 56.0127591707,
"line_max": 120,
"alpha_frac": 0.6207234173,
"autogenerated": false,
"ratio": 3.803681634390296,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4924405051690296,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_analytics.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from analytics.controllers import save_analytics_action_for_api
from analytics.models import ACTIONS_THAT_REQUIRE_ORGANIZATION_IDS
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from organization.models import OrganizationManager
import robot_detection
from django_user_agents.utils import get_user_agent
from voter.models import VoterDeviceLinkManager, VoterManager
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_voter_device_id, is_voter_device_id_valid, \
positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def save_analytics_action_view(request): # saveAnalyticsAction
status = ""
success = False
missing_required_variable = False
voter_id = 0
voter_we_vote_id = ""
is_signed_in = False
state_code_from_ip_address = "" # If a state_code is NOT passed in, we want to get the state_code from ip address
voter_device_id_for_storage = ""
date_as_integer = 0
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
action_constant = convert_to_int(request.GET.get('action_constant', 0))
state_code = request.GET.get('state_code', '') # If a state code is passed in, we want to use it
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
organization_id = convert_to_int(request.GET.get('organization_id', 0))
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', '')
user_agent_string = request.META['HTTP_USER_AGENT']
# robot-detection is used for detecting web bots only and django-user-agents is used for device detection
user_agent_object = get_user_agent(request)
is_bot = user_agent_object.is_bot or robot_detection.is_robot(user_agent_string)
is_mobile = user_agent_object.is_mobile
is_desktop = user_agent_object.is_pc
is_tablet = user_agent_object.is_tablet
# We use the lighter call to VoterDeviceLinkManager instead of VoterManager until we know there is an entry
voter_device_link_manager = VoterDeviceLinkManager()
results = voter_device_link_manager.retrieve_voter_device_link_from_voter_device_id(voter_device_id,
read_only=True)
if results['voter_device_link_found']:
voter_device_link = results['voter_device_link']
voter_id = voter_device_link.voter_id
state_code_from_ip_address = voter_device_link.state_code
voter_manager = VoterManager()
voter_results = voter_manager.retrieve_voter_by_id(voter_id)
if positive_value_exists(voter_results['voter_found']):
voter = voter_results['voter']
voter_we_vote_id = voter.we_vote_id
is_signed_in = voter.is_signed_in()
else:
voter_device_id_for_storage = voter_device_id
action_requires_organization_ids = True if action_constant in ACTIONS_THAT_REQUIRE_ORGANIZATION_IDS else False
if action_requires_organization_ids:
# If here, make sure we have both organization ids
organization_manager = OrganizationManager()
if positive_value_exists(organization_we_vote_id) and not positive_value_exists(organization_id):
organization_id = organization_manager.fetch_organization_id(organization_we_vote_id)
elif positive_value_exists(organization_id) and not positive_value_exists(organization_we_vote_id):
organization_we_vote_id = organization_manager.fetch_we_vote_id_from_local_id(organization_id)
if not positive_value_exists(organization_we_vote_id):
status += "MISSING_ORGANIZATION_WE_VOTE_ID "
success = False
missing_required_variable = True
if not positive_value_exists(organization_id):
status += "MISSING_ORGANIZATION_ID "
success = False
missing_required_variable = True
if not positive_value_exists(state_code):
state_code = state_code_from_ip_address
if missing_required_variable:
json_data = {
'status': status,
'success': success,
'voter_device_id': voter_device_id,
'action_constant': action_constant,
'state_code': state_code,
'is_signed_in': is_signed_in,
'google_civic_election_id': google_civic_election_id,
'organization_we_vote_id': organization_we_vote_id,
'organization_id': organization_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
'date_as_integer': date_as_integer,
'user_agent': user_agent_string,
'is_bot': is_bot,
'is_mobile': is_mobile,
'is_desktop': is_desktop,
'is_tablet': is_tablet,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = save_analytics_action_for_api(action_constant, voter_we_vote_id, voter_id, is_signed_in, state_code,
organization_we_vote_id, organization_id, google_civic_election_id,
user_agent_string, is_bot, is_mobile, is_desktop, is_tablet,
ballot_item_we_vote_id, voter_device_id_for_storage)
status += results['status']
json_data = {
'status': status,
'success': results['success'],
'voter_device_id': voter_device_id,
'action_constant': action_constant,
'state_code': state_code,
'is_signed_in': is_signed_in,
'google_civic_election_id': google_civic_election_id,
'organization_we_vote_id': organization_we_vote_id,
'organization_id': organization_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
'date_as_integer': results['date_as_integer'],
'user_agent': user_agent_string,
'is_bot': is_bot,
'is_mobile': is_mobile,
'is_desktop': is_desktop,
'is_tablet': is_tablet,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_analytics.py",
"copies": "2",
"size": "6801",
"license": "mit",
"hash": -7309852727518212000,
"line_mean": 50.1353383459,
"line_max": 118,
"alpha_frac": 0.6174092045,
"autogenerated": false,
"ratio": 3.6782044348296377,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001453387621514087,
"num_lines": 133
} |
# apis_v1/views/views_apple.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from exception.models import print_to_log, handle_exception
import json
from apple.AppleResolver import AppleResolver
from apple.controllers import apple_sign_in_save_merge_if_needed, \
validate_sign_in_with_apple_token_for_api # apple_sign_in_retrieve_voter_id,
from apple.models import AppleUser
from config.base import get_environment_variable, get_environment_variable_default
from voter.models import VoterDeviceLinkManager, VoterManager # fetch_voter_we_vote_id_from_voter_device_link,
from wevote_functions.functions import get_voter_device_id, positive_value_exists
import wevote_functions.admin
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def sign_in_with_apple_view(request): # appleSignInSave appleSignInSaveView
"""
Handle and store the data from a "Sign In With Apple" login in iOS through Cordova
:param request:
:return:
"""
status = ""
status += "STARTING-appleSignInSave "
previously_signed_in_voter = None
previously_signed_in_voter_found = False
previously_signed_in_voter_we_vote_id = ''
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
user_code = request.GET.get('user_code', '')
identity_token = request.GET.get('identity_token', '')
email = request.GET.get('email', '')
first_name = request.GET.get('first_name', '')
middle_name = request.GET.get('middle_name', '')
last_name = request.GET.get('last_name', '')
apple_platform = request.GET.get('apple_platform', '')
apple_os_version = request.GET.get('apple_os_version', '')
apple_model = request.GET.get('apple_model', '')
# voter_we_vote_id = request.GET.get('voter_we_vote_id', '')
if not positive_value_exists(email):
client_id = get_environment_variable_default('SOCIAL_AUTH_APPLE_CLIENT_ID_IOS', 'org.wevote.cordova')
results = AppleResolver().authenticate(identity_token, client_id)
if results:
user_code = results['subject_registered_claim']
email = results['email']
# for a splunk trail...
# logger.error("splunkapple Not an error: Sign in with Apple iOS, decrypted jwt: " + user_code + " " + email)
voter_manager = VoterManager()
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_id = get_voter_device_id(request)
results = voter_device_link_manager.retrieve_voter_device_link(
voter_device_id, read_only=False)
if results['voter_device_link_found']:
voter_device_link = results['voter_device_link']
else:
voter_device_link = None
results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id, read_only=False)
if results['voter_found']:
# This is the voter account the person is using when they click "Sign in with Apple"
voter_starting_process = results['voter']
voter_starting_process_we_vote_id = voter_starting_process.we_vote_id
else:
voter_starting_process = None
voter_starting_process_we_vote_id = ''
if not positive_value_exists(voter_starting_process_we_vote_id):
status += "VOTER_WE_VOTE_ID_FROM_VOTER_STARTING_PROCESS_MISSING "
json_data = {
'status': status,
'success': False,
'previously_signed_in_voter': previously_signed_in_voter,
'previously_signed_in_voter_found': previously_signed_in_voter_found,
'previously_signed_in_voter_we_vote_id': previously_signed_in_voter_we_vote_id,
}
# logger.error('splunkapple ' + status)
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = sign_in_with_apple_for_api(
user_code=user_code,
email=email,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
apple_platform=apple_platform,
apple_os_version=apple_os_version,
apple_model=apple_model,
voter_starting_process_we_vote_id=voter_starting_process_we_vote_id)
status += results['status']
merge_results = apple_sign_in_save_merge_if_needed(
email_from_apple=email,
previously_signed_in_apple_voter_found=results['previously_signed_in_voter_found'],
previously_signed_in_apple_voter_we_vote_id=results['previously_signed_in_voter_we_vote_id'],
voter_device_link=voter_device_link,
voter_starting_process=voter_starting_process,
)
status += merge_results['status']
# logger.error('splunkapple ' + status)
json_data = {
'status': status,
'success': True,
'previously_signed_in_voter': previously_signed_in_voter,
'previously_signed_in_voter_found': previously_signed_in_voter_found,
'previously_signed_in_voter_we_vote_id': previously_signed_in_voter_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def payload(message, status):
return HttpResponse(
json.dumps({"status": status, "payload": message} if message is not None else {"status": status})
)
def success(message=None):
return payload(message, "success")
def sign_in_with_apple_for_api(
user_code='',
email='',
first_name='',
middle_name='',
last_name='',
apple_platform='',
apple_os_version='',
apple_model='',
voter_starting_process_we_vote_id=''):
status = ""
success_siwa = False
previously_signed_in_voter_found = False
previously_signed_in_voter_we_vote_id = ''
signed_in_voter_we_vote_id = ''
if not positive_value_exists(user_code):
status += "CREATE_APPLE_USER_MISSING_REQUIRED_VARIABLE_USER_CODE "
print_to_log(logger=logger, exception_message_optional=status)
results = {
'success': success_siwa,
'status': status,
'previously_signed_in_voter_found': '',
'previously_signed_in_voter_we_vote_id': '',
'signed_in_voter_we_vote_id': '',
}
return results
#
# The presence of a matching voter_device_id indicates signed in status on the specific device
#
try:
# I may need to delete any row prior to this change 8/14/20
# Force kill any legacy duplicates, from now on only one row per user code
# to test this you will have to navigate to https://appleid.apple.com/account/manage
# and remove the wevote cordova app from the list
# usr = AppleUser.objects.filter(user_code=user_code)[:1].values_list("id", flat=True) # only retrieve ids.
# AppleUser.objects.exclude(pk__in=list(usr)).delete()
# Get the last row that matches user_code
apple_user = AppleUser.objects.filter(user_code=user_code).last()
if apple_user:
status += "APPLE_USER_ID_RECORD_UPDATED "
previously_signed_in_voter_found = True
previously_signed_in_voter_we_vote_id = apple_user.voter_we_vote_id
signed_in_voter_we_vote_id = apple_user.voter_we_vote_id
else:
# user_code not found: Create new AppleUser entry
# if not last_name:
# apple_user_first = AppleUser.objects.filter(user_code=user_code).first()
# first_name = apple_user_first.first_name
# middle_name = apple_user_first.middle_name
# last_name = apple_user_first.last_name
apple_user = AppleUser.objects.create(
email=email,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
apple_platform=apple_platform,
apple_os_version=apple_os_version,
apple_model=apple_model,
voter_we_vote_id=voter_starting_process_we_vote_id,
user_code=user_code,
)
status += "APPLE_USER_ID_RECORD_CREATED "
previously_signed_in_voter_found = False
previously_signed_in_voter_we_vote_id = ''
signed_in_voter_we_vote_id = apple_user.voter_we_vote_id
# If you Signed in with Apple first on another device, and we didn't catch the email or name the first time
# through, catch them on subsequent "first sign ins on a device"
if not positive_value_exists(apple_user.email) and positive_value_exists(email):
apple_user.email = email
if not positive_value_exists(apple_user.first_name) and positive_value_exists(first_name):
apple_user.first_name = first_name
if not positive_value_exists(apple_user.middle_name) and positive_value_exists(middle_name):
apple_user.middle_name = middle_name
if not positive_value_exists(apple_user.last_name) and positive_value_exists(last_name):
apple_user.last_name = last_name
apple_user.date_last_referenced = datetime.today()
# We match to existing voter outside of this function
# if not positive_value_exists(previously_signed_in_voter_we_vote_id):
# results_id = apple_sign_in_retrieve_voter_id(email, first_name, last_name)
# if positive_value_exists(results_id['voter_we_vote_id']):
# previously_signed_in_voter_we_vote_id = results_id['voter_we_vote_id']
# apple_user.voter_we_vote_id = previously_signed_in_voter_we_vote_id
# status += previously_signed_in_voter_we_vote_id + " " + results_id['status'] + " "
apple_user.save()
success_siwa = True
except Exception as e:
success_siwa = False
status += "ERROR_APPLE_USER_NOT_CREATED_OR_UPDATED: " + str(e) + ' '
handle_exception(e, logger=logger, exception_message=status)
results = {
'success': success_siwa,
'status': status,
'previously_signed_in_voter_found': previously_signed_in_voter_found,
'previously_signed_in_voter_we_vote_id': previously_signed_in_voter_we_vote_id,
'signed_in_voter_we_vote_id': signed_in_voter_we_vote_id,
}
return results
@csrf_exempt
def sign_in_with_apple_oauth_redirect_view(request): # appleSignInOauthRedirectDestination
# This is part of the OAuth flow for the WebApp (This is NOT part of the flow for iOS!)
status = ''
status += "STARTING-appleSignInOauthRedirectDestination "
access_token = ''
critical_variable_missing = False
first_name = ''
middle_name = ''
last_name = ''
email = ''
return_url = ''
user_code = ''
voter_device_id = ''
print("Method is", request.method)
if not request.method == 'POST':
logger.error('splunkapple appleSignInOauthRedirectDestination WRONG Method: ' + request.method)
try:
access_token = request.POST['id_token']
except Exception as e:
status += "ID_TOKEN_MISSING: " + str(e) + ' '
critical_variable_missing = True
try:
state_dict = json.loads(request.POST['state'])
voter_device_id = state_dict['voter_device_id']
return_url = state_dict['return_url']
except Exception as e:
status += "STATE_DICT_MISSING: " + str(e) + ' '
critical_variable_missing = True
# print('id_token renamed as access_token: ', access_token)
if critical_variable_missing:
logger.error('splunkapple ' + status)
return HttpResponseRedirect('https://WeVote.US/applesigninprocess')
if 'user' in request.POST:
# Apple only sends this user name in the clear on the very first time the voter signs in with Apple on a device
# <QueryDict: {
# 'state': [
# '{"voter_device_id":"WHEQYCQ...hWFUs6RJ1k",
# "return_url":"https://localhost:3000/ready"}'
# ],
# 'code': ['cfd1436ca8c8d463d94e55f4a2bdbfbf8.0.nruqx.bg8M64KEkoUOBwmddufJLA'],
# 'id_token': ['eyJraW...JO4aJMpGGtN2q8L1kJG7AQV1sgRg'],
# 'user': [
# '{"name":
# {"firstName":"Steve",
# "lastName":"Podell"},
# "email":"stevepodell11@yahoo.com"}'
# ]}>
# On subsequent calls it looks like
# <QueryDict: {
# 'state': [
# '{"voter_device_id": "eHUgOyy...8ho2uvPZWmGY4mNWNn6U9VKVhthrh7MHiurhNwwDoirgSR",
# "return_url":"https://localhost:3000/ready"}'
# ],
# 'code': ['cfd1436ca8c8d463d94e55f4a2bdbfbf8.0.nruqx.bg8M64KEkoUOBwmddufJLA'],
# 'id_token': ['eyJraW...JO4aJMpGGtN2q8L1kJG7AQV1sgRg'],
# But the voter's email that is registered with SIWA is received encrypted in the id_token on subsequent logins
# To re-test the initial login message, goto https://appleid.apple.com/account/manage and under
# Security/"APPS & WEBSITES USING APPLE ID" click "Manage..." and "Stop Using Apple ID" for
# "We Vote Ballot Guide, @WeVote"
user_string = request.POST['user']
user = json.loads(user_string)
if 'firstName' in user['name']:
first_name = user['name']['firstName']
if 'middleName' in user['name']:
middle_name = user['name']['middleName']
if 'lastName' in user['name']:
last_name = user['name']['lastName']
if 'email' in user:
email = user['email']
client_id = get_environment_variable_default('SOCIAL_AUTH_APPLE_CLIENT_ID_WEB', 'us.wevote.webapp')
results = AppleResolver().authenticate(access_token, client_id)
if results:
user_code = results['subject_registered_claim']
email = results['email']
# for a splunk trail...
# logger.error("splunkapple Not an error: Sign in with Apple WebApp, decrypted jwt", results)
# voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
voter_manager = VoterManager()
voter_device_link_manager = VoterDeviceLinkManager()
results = voter_device_link_manager.retrieve_voter_device_link(
voter_device_id, read_only=False)
if results['voter_device_link_found']:
voter_device_link = results['voter_device_link']
else:
voter_device_link = None
results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id, read_only=False)
if results['voter_found']:
# This is the voter account the person is using when they click "Sign in with Apple"
voter_starting_process = results['voter']
voter_starting_process_we_vote_id = voter_starting_process.we_vote_id
else:
voter_starting_process = None
voter_starting_process_we_vote_id = ''
if not positive_value_exists(voter_starting_process_we_vote_id):
logger.error(
'splunkapple did not receive a voter_we_vote_id from voter_device_id in sign_in_with_apple_oauth_redirect_view ')
results = sign_in_with_apple_for_api(
user_code=user_code,
email=email,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
apple_platform='Web WeVoteWebApp',
apple_os_version='n/a',
apple_model='n/a',
voter_starting_process_we_vote_id=voter_starting_process_we_vote_id)
status += results['status']
merge_results = apple_sign_in_save_merge_if_needed(
email_from_apple=email,
previously_signed_in_apple_voter_found=results['previously_signed_in_voter_found'],
previously_signed_in_apple_voter_we_vote_id=results['previously_signed_in_voter_we_vote_id'],
voter_device_link=voter_device_link,
voter_starting_process=voter_starting_process,
)
status += merge_results['status']
# logger.error('splunkapple ' + status)
return HttpResponseRedirect(return_url)
def validate_sign_in_with_apple_token(request): # appleValidateSignInWithAppleToken
"""
Handle and store the data from a "Sign In With Apple" login via the WebApp
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
apple_oauth_code = request.GET.get('code', '')
results = validate_sign_in_with_apple_token_for_api(
apple_oauth_code=apple_oauth_code,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_we_vote_id': results['voter_we_vote_id'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_apple.py",
"copies": "1",
"size": "17147",
"license": "mit",
"hash": 1220516328548887300,
"line_mean": 43.1932989691,
"line_max": 125,
"alpha_frac": 0.6291479559,
"autogenerated": false,
"ratio": 3.4252896524170993,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9547043450022727,
"avg_score": 0.0014788316588745483,
"num_lines": 388
} |
# apis_v1/views/views_ballot.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from ballot.controllers import all_ballot_items_retrieve_for_api, ballot_item_highlights_retrieve_for_api, \
ballot_item_options_retrieve_for_api, ballot_items_search_retrieve_for_api
from candidate.controllers import candidate_retrieve_for_api
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from measure.controllers import measure_retrieve_for_api
from office.controllers import office_retrieve_for_api
from ballot.models import OFFICE, CANDIDATE, MEASURE
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, positive_value_exists, get_voter_device_id
from voter.controllers import email_ballot_data_for_api
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def all_ballot_items_retrieve_view(request): # allBallotItemsRetrieve
"""
Return all the ballot data requested for an election
:param request:
:return:
"""
# If passed in, we want to look at
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
state_code = request.GET.get('state_code', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
if use_test_election:
google_civic_election_id = 2000 # The Google Civic test election
json_data = all_ballot_items_retrieve_for_api(google_civic_election_id, state_code)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def ballot_item_highlights_retrieve_view(request): # ballotItemHighlightsRetrieve
json_data = ballot_item_highlights_retrieve_for_api()
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
def ballot_item_options_retrieve_view(request): # ballotItemOptionsRetrieve
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
search_string = request.GET.get('search_string', '')
state_code = request.GET.get('state_code', '')
results = ballot_item_options_retrieve_for_api(google_civic_election_id, search_string, state_code)
response = HttpResponse(json.dumps(results['json_data']), content_type='application/json')
return response
def ballot_item_retrieve_view(request): # ballotItemRetrieve
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', '')
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if not positive_value_exists(kind_of_ballot_item) or kind_of_ballot_item not in (OFFICE, CANDIDATE, MEASURE):
status = 'VALID_BALLOT_ITEM_TYPE_MISSING'
json_data = {
'status': status,
'success': False,
'kind_of_ballot_item': kind_of_ballot_item,
'ballot_item_id': ballot_item_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if kind_of_ballot_item == OFFICE:
return office_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
elif kind_of_ballot_item == CANDIDATE:
return candidate_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
elif kind_of_ballot_item == MEASURE:
return measure_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
else:
status = 'BALLOT_ITEM_RETRIEVE_UNKNOWN_ERROR'
json_data = {
'status': status,
'success': False,
'kind_of_ballot_item': kind_of_ballot_item,
'ballot_item_id': ballot_item_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def ballot_items_search_retrieve_view(request): # ballotItemsSearchRetrieve
"""
Return ballot search results
NOT FULLY IMPLEMENTED -- See ballotItemOptionsRetrieve instead
:param request:
:return:
"""
# google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0)) # Convert to list
search_string = request.GET.get('search_string', '')
# state_code = request.GET.get('state_code', '') # Convert to list
json_data = ballot_items_search_retrieve_for_api(search_string)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def email_ballot_data_view(request): # emailBallotData
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_address_array = request.GET.getlist('email_address_array[]', "")
first_name_array = request.GET.getlist('first_name_array[]', "")
last_name_array = request.GET.getlist('last_name_array[]', "")
email_addresses_raw = request.GET.get('email_addresses_raw', "")
invitation_message = request.GET.get('invitation_message', "")
ballot_link = request.GET.get('ballot_link', "")
sender_email_address = request.GET.get('sender_email_address', "")
verification_email_sent = positive_value_exists(request.GET.get('verification_email_sent', False))
hostname = request.GET.get('hostname', "")
results = email_ballot_data_for_api(voter_device_id, email_address_array, first_name_array,
last_name_array, email_addresses_raw,
invitation_message, ballot_link, sender_email_address,
verification_email_sent,
web_app_root_url=hostname)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'sender_voter_email_address_missing': results['sender_voter_email_address_missing'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_ballot.py",
"copies": "1",
"size": "6298",
"license": "mit",
"hash": -3376968477361722400,
"line_mean": 46.3533834586,
"line_max": 114,
"alpha_frac": 0.6590981264,
"autogenerated": false,
"ratio": 3.4452954048140043,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.959644736804778,
"avg_score": 0.001589232633245003,
"num_lines": 133
} |
# apis_v1/views/views_ballot.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from ballot.controllers import ballot_item_options_retrieve_for_api
from candidate.controllers import candidate_retrieve_for_api
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from measure.controllers import measure_retrieve_for_api
from office.controllers import office_retrieve_for_api
from ballot.models import OFFICE, CANDIDATE, MEASURE
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, positive_value_exists, get_voter_device_id
from voter.controllers import email_ballot_data_for_api
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def ballot_item_options_retrieve_view(request): # ballotItemOptionsRetrieve
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
search_string = request.GET.get('search_string', '')
state_code = request.GET.get('state_code', '')
results = ballot_item_options_retrieve_for_api(google_civic_election_id, search_string, state_code)
response = HttpResponse(json.dumps(results['json_data']), content_type='application/json')
return response
def ballot_item_retrieve_view(request): # ballotItemRetrieve
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', '')
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if not positive_value_exists(kind_of_ballot_item) or kind_of_ballot_item not in(OFFICE, CANDIDATE, MEASURE):
status = 'VALID_BALLOT_ITEM_TYPE_MISSING'
json_data = {
'status': status,
'success': False,
'kind_of_ballot_item': kind_of_ballot_item,
'ballot_item_id': ballot_item_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if kind_of_ballot_item == OFFICE:
return office_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
elif kind_of_ballot_item == CANDIDATE:
return candidate_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
elif kind_of_ballot_item == MEASURE:
return measure_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
else:
status = 'BALLOT_ITEM_RETRIEVE_UNKNOWN_ERROR'
json_data = {
'status': status,
'success': False,
'kind_of_ballot_item': kind_of_ballot_item,
'ballot_item_id': ballot_item_id,
'ballot_item_we_vote_id': ballot_item_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def email_ballot_data_view(request): # emailBallotData
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_address_array = request.GET.getlist('email_address_array[]', "")
first_name_array = request.GET.getlist('first_name_array[]', "")
last_name_array = request.GET.getlist('last_name_array[]', "")
email_addresses_raw = request.GET.get('email_addresses_raw', "")
invitation_message = request.GET.get('invitation_message', "")
ballot_link = request.GET.get('ballot_link', "")
sender_email_address = request.GET.get('sender_email_address', "")
verification_email_sent = positive_value_exists(request.GET.get('verification_email_sent', False))
results = email_ballot_data_for_api(voter_device_id, email_address_array, first_name_array,
last_name_array, email_addresses_raw,
invitation_message, ballot_link, sender_email_address,
verification_email_sent)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'sender_voter_email_address_missing': results['sender_voter_email_address_missing'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_ballot.py",
"copies": "1",
"size": "4469",
"license": "mit",
"hash": 6380296267698609000,
"line_mean": 49.2134831461,
"line_max": 112,
"alpha_frac": 0.6442157082,
"autogenerated": false,
"ratio": 3.4271472392638036,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45713629474638034,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_campaign.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from campaign.controllers import campaignx_list_retrieve_for_api, campaignx_retrieve_for_api, campaignx_save_for_api, \
campaignx_supporter_retrieve_for_api, campaignx_supporter_save_for_api
from config.base import get_environment_variable
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django_user_agents.utils import get_user_agent
from exception.models import handle_exception
from follow.controllers import voter_campaignx_follow_for_api
import json
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def campaignx_list_retrieve_view(request): # campaignListRetrieve (No CDN)
hostname = request.GET.get('hostname', '')
recommended_campaigns_for_campaignx_we_vote_id = \
request.GET.get('recommended_campaigns_for_campaignx_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
json_data = campaignx_list_retrieve_for_api(
request=request,
hostname=hostname,
recommended_campaigns_for_campaignx_we_vote_id=recommended_campaigns_for_campaignx_we_vote_id,
voter_device_id=voter_device_id,
)
json_string = ''
try:
# March 24, 2021: Throwing "TypeError: Object of type 'HttpResponse' is not JSON serializable"
json_string = json.dumps(json_data)
except Exception as e:
status = "Caught error for voter_device_id " + voter_device_id
handle_exception(e, logger=logger, exception_message=status)
return HttpResponse(json_string, content_type='application/json')
def campaignx_supporter_retrieve_view(request): # campaignSupporterRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
campaignx_we_vote_id = request.GET.get('campaignx_we_vote_id', '')
json_data = campaignx_supporter_retrieve_for_api(
voter_device_id=voter_device_id,
campaignx_we_vote_id=campaignx_we_vote_id,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def campaignx_retrieve_view(request): # campaignRetrieve (CDN)
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
campaignx_we_vote_id = request.GET.get('campaignx_we_vote_id', '')
hostname = request.GET.get('hostname', '')
seo_friendly_path = request.GET.get('seo_friendly_path', '')
json_data = campaignx_retrieve_for_api(
request=request,
voter_device_id=voter_device_id,
campaignx_we_vote_id=campaignx_we_vote_id,
hostname=hostname,
seo_friendly_path=seo_friendly_path,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def campaignx_retrieve_as_owner_view(request): # campaignRetrieveAsOwner (No CDN)
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
campaignx_we_vote_id = request.GET.get('campaignx_we_vote_id', '')
hostname = request.GET.get('hostname', '')
json_data = campaignx_retrieve_for_api(
request=request,
voter_device_id=voter_device_id,
campaignx_we_vote_id=campaignx_we_vote_id,
as_owner=True,
hostname=hostname,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
@csrf_exempt
def campaignx_save_view(request): # campaignSave & campaignStartSave
# This is set in /config/base.py: DATA_UPLOAD_MAX_MEMORY_SIZE = 6000000
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
campaign_description = request.POST.get('campaign_description', '')
campaign_description_changed = positive_value_exists(request.POST.get('campaign_description_changed', False))
in_draft_mode = positive_value_exists(request.POST.get('in_draft_mode', True))
in_draft_mode_changed = positive_value_exists(request.POST.get('in_draft_mode_changed', False))
campaign_photo_from_file_reader = request.POST.get('campaign_photo_from_file_reader', '')
campaign_photo_changed = positive_value_exists(request.POST.get('campaign_photo_changed', False))
campaign_title = request.POST.get('campaign_title', '')
campaign_title_changed = positive_value_exists(request.POST.get('campaign_title_changed', False))
campaignx_we_vote_id = request.POST.get('campaignx_we_vote_id', '')
politician_delete_list_serialized = request.POST.get('politician_delete_list', '')
politician_starter_list_serialized = request.POST.get('politician_starter_list', '')
politician_starter_list_changed = positive_value_exists(request.POST.get('politician_starter_list_changed', False))
json_data = campaignx_save_for_api(
campaign_description=campaign_description,
campaign_description_changed=campaign_description_changed,
in_draft_mode=in_draft_mode,
in_draft_mode_changed=in_draft_mode_changed,
campaign_photo_from_file_reader=campaign_photo_from_file_reader,
campaign_photo_changed=campaign_photo_changed,
campaign_title=campaign_title,
campaign_title_changed=campaign_title_changed,
campaignx_we_vote_id=campaignx_we_vote_id,
politician_delete_list_serialized=politician_delete_list_serialized,
politician_starter_list_serialized=politician_starter_list_serialized,
politician_starter_list_changed=politician_starter_list_changed,
voter_device_id=voter_device_id,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def campaignx_supporter_save_view(request): # campaignSupporterSave
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
supporter_endorsement = request.GET.get('supporter_endorsement', '')
supporter_endorsement_changed = positive_value_exists(request.GET.get('supporter_endorsement_changed', False))
visible_to_public = positive_value_exists(request.GET.get('visible_to_public', True))
visible_to_public_changed = positive_value_exists(request.GET.get('visible_to_public_changed', False))
campaign_supported = positive_value_exists(request.GET.get('campaign_supported', False))
campaign_supported_changed = positive_value_exists(request.GET.get('campaign_supported_changed', False))
campaignx_we_vote_id = request.GET.get('campaignx_we_vote_id', '')
json_data = campaignx_supporter_save_for_api(
campaignx_we_vote_id=campaignx_we_vote_id,
campaign_supported=campaign_supported,
campaign_supported_changed=campaign_supported_changed,
supporter_endorsement=supporter_endorsement,
supporter_endorsement_changed=supporter_endorsement_changed,
visible_to_public=visible_to_public,
visible_to_public_changed=visible_to_public_changed,
voter_device_id=voter_device_id,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_campaignx_follow_view(request): # campaignFollow
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
issue_we_vote_id = request.GET.get('issue_we_vote_id', False)
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
follow_value = positive_value_exists(request.GET.get('follow', False))
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
ignore_value = positive_value_exists(request.GET.get('ignore', False))
result = voter_campaignx_follow_for_api(
voter_device_id=voter_device_id,
issue_we_vote_id=issue_we_vote_id,
follow_value=follow_value,
ignore_value=ignore_value, user_agent_string=user_agent_string,
user_agent_object=user_agent_object)
result['google_civic_election_id'] = google_civic_election_id
return HttpResponse(json.dumps(result), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_campaign.py",
"copies": "1",
"size": "8263",
"license": "mit",
"hash": -297616346298878850,
"line_mean": 52.3096774194,
"line_max": 119,
"alpha_frac": 0.7237080963,
"autogenerated": false,
"ratio": 3.3331988705123035,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4556906966812303,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_candidate.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from candidate.controllers import candidate_retrieve_for_api, candidates_retrieve_for_api, \
retrieve_candidate_list_for_all_upcoming_elections
from candidate.views_admin import candidate_change_names
from politician.views_admin import politician_change_names
from django.contrib.auth.decorators import login_required
from config.base import get_environment_variable
from django.http import HttpResponse
import json
import wevote_functions.admin
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def candidate_retrieve_view(request): # candidateRetrieve
candidate_id = request.GET.get('candidate_id', 0)
candidate_we_vote_id = request.GET.get('candidate_we_vote_id', None)
return candidate_retrieve_for_api(candidate_id, candidate_we_vote_id)
def candidates_retrieve_view(request): # candidatesRetrieve
office_id = request.GET.get('office_id', 0)
office_we_vote_id = request.GET.get('office_we_vote_id', '')
return candidates_retrieve_for_api(office_id, office_we_vote_id)
def candidate_list_for_upcoming_elections_retrieve_api_view(request): # candidateListForUpcomingElectionsRetrieve
"""
Ask for all candidates running for the elections in google_civic_election_id_list
:param request:
:return:
"""
status = ""
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list[]')
state_code = request.GET.get('state_code', '')
# We will need all candidates for all upcoming elections so we can search the HTML of
# the possible voter guide for these names
candidate_list_light = []
super_light = True # limit the response package
results = retrieve_candidate_list_for_all_upcoming_elections(google_civic_election_id_list,
limit_to_this_state_code=state_code,
super_light_candidate_list=super_light)
if results['candidate_list_found']:
candidate_list_light = results['candidate_list_light']
google_civic_election_id_list = results['google_civic_election_id_list']
status += results['status']
success = results['success']
json_data = {
'status': status,
'success': success,
'google_civic_election_id_list': google_civic_election_id_list,
'candidate_list': candidate_list_light,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
@login_required
def candidate_or_politician_repair_names(request): # candidateOrPoliticianRepairNames
"""
Change the names of misformatted candidates or politicians
:param request:
:return:
"""
status = ""
is_candidate = True
body = request.body.decode('utf-8')
payload = json.loads(body)
is_candidate = payload['is_candidate']
changes = payload['changes']
if is_candidate:
return_count = candidate_change_names(changes)
else:
return_count = politician_change_names(changes)
json_data = {
'count': return_count,
'success': return_count > 0,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_candidate.py",
"copies": "1",
"size": "3493",
"license": "mit",
"hash": 5854225030299931000,
"line_mean": 38.2471910112,
"line_max": 114,
"alpha_frac": 0.659891211,
"autogenerated": false,
"ratio": 3.7640086206896552,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9862415841798897,
"avg_score": 0.012296797978151563,
"num_lines": 89
} |
# apis_v1/views/views_docs.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from apis_v1.documentation_source import ballot_item_options_retrieve_doc, ballot_item_retrieve_doc, \
ballot_items_sync_out_doc, ballot_returned_sync_out_doc, \
candidate_retrieve_doc, \
candidates_retrieve_doc, candidates_sync_out_doc, device_id_generate_doc, donation_with_stripe_doc, \
elections_retrieve_doc, elections_sync_out_doc, facebook_disconnect_doc, facebook_friends_action_doc, \
friend_invitation_by_email_send_doc, \
friend_invitation_by_email_verify_doc, friend_invitation_by_we_vote_id_send_doc, \
friend_invitation_by_facebook_send_doc, friend_invitation_by_facebook_verify_doc, \
friend_invite_response_doc, friend_list_doc, issue_follow_doc, issues_retrieve_doc, issues_sync_out_doc, \
issues_linked_to_organization_doc, issues_to_link_to_for_organization_doc, \
measure_retrieve_doc, measures_sync_out_doc, \
office_retrieve_doc, offices_sync_out_doc, \
organization_count_doc, organizations_followed_retrieve_doc, \
organization_follow_doc, organization_follow_ignore_doc, \
organization_link_to_issue_sync_out_doc, organization_link_to_issue_doc, organization_stop_following_doc, \
organization_retrieve_doc, organization_save_doc, organization_search_doc, organizations_sync_out_doc, \
organization_suggestion_tasks_doc, \
pledge_to_vote_with_voter_guide_doc, politicians_sync_out_doc, polling_locations_sync_out_doc, \
position_like_count_doc, position_list_for_ballot_item_doc, position_list_for_opinion_maker_doc, \
position_list_for_voter_doc, position_oppose_count_for_ballot_item_doc, \
position_public_oppose_count_for_ballot_item_doc, position_retrieve_doc, position_save_doc, \
positions_sync_out_doc, \
position_public_support_count_for_ballot_item_doc, position_support_count_for_ballot_item_doc, \
positions_count_for_all_ballot_items_doc, positions_count_for_one_ballot_item_doc, \
quick_info_retrieve_doc, retrieve_issues_to_follow_doc, \
save_analytics_action_doc, search_all_doc, twitter_identity_retrieve_doc, \
twitter_sign_in_request_access_token_doc, twitter_sign_in_request_voter_info_doc, twitter_sign_in_retrieve_doc, \
twitter_sign_in_start_doc, twitter_retrieve_ids_i_follow_doc, voter_address_retrieve_doc, voter_address_save_doc, \
voter_all_positions_retrieve_doc, voter_all_bookmarks_status_retrieve_doc, \
voter_ballot_items_retrieve_doc, \
voter_ballot_items_retrieve_from_google_civic_doc, voter_ballot_list_retrieve_doc, \
voter_bookmark_off_save_doc, \
voter_bookmark_on_save_doc, voter_bookmark_status_retrieve_doc, \
voter_count_doc, voter_create_doc, voter_email_address_retrieve_doc, voter_email_address_save_doc, \
voter_email_address_sign_in_doc, voter_email_address_verify_doc, voter_facebook_save_to_current_account_doc, \
voter_facebook_sign_in_retrieve_doc, voter_facebook_sign_in_save_doc, \
voter_follow_all_organizations_followed_by_organization_doc, \
voter_guide_possibility_retrieve_doc, voter_guide_possibility_save_doc, \
voter_guides_followed_retrieve_doc, voter_guides_followed_by_organization_retrieve_doc, \
voter_guide_followers_retrieve_doc, voter_guide_save_doc, voter_guides_ignored_retrieve_doc, \
voter_guides_retrieve_doc, voter_guides_sync_out_doc, voter_guides_to_follow_retrieve_doc, \
voter_guides_upcoming_retrieve_doc, \
voter_location_retrieve_from_ip_doc, voter_merge_two_accounts_doc, voter_photo_save_doc, \
voter_position_like_off_save_doc, voter_position_like_on_save_doc, voter_position_like_status_retrieve_doc, \
voter_position_comment_save_doc, voter_position_retrieve_doc, voter_position_visibility_save_doc, \
voter_opposing_save_doc, voter_retrieve_doc, voter_sign_out_doc, voter_split_into_two_accounts_doc, \
voter_stop_opposing_save_doc, \
voter_stop_supporting_save_doc, voter_supporting_save_doc, voter_twitter_save_to_current_account_doc, \
voter_update_doc, email_ballot_data_doc
from config.base import get_environment_variable
from django.contrib.messages import get_messages
from django.shortcuts import render
from voter.models import voter_setup
from wevote_functions.functions import get_voter_api_device_id, set_voter_api_device_id, positive_value_exists
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def apis_index_doc_view(request):
"""
Show a list of available APIs
"""
# Create a voter_device_id and voter in the database if one doesn't exist yet
results = voter_setup(request)
voter_api_device_id = results['voter_api_device_id']
store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']
messages_on_stage = get_messages(request)
template_values = {
'next': next,
'messages_on_stage': messages_on_stage,
}
response = render(request, 'apis_v1/apis_index.html', template_values)
# We want to store the voter_device_id cookie if it is new
if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
set_voter_api_device_id(request, response, voter_api_device_id)
return response
def ballot_item_options_retrieve_doc_view(request):
"""
Show documentation about ballotItemOptionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_options_retrieve_doc.ballot_item_options_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_item_retrieve_doc_view(request):
"""
Show documentation about ballotItemRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_retrieve_doc.ballot_item_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_items_sync_out_doc_view(request):
"""
Show documentation about ballotItemsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_items_sync_out_doc.ballot_items_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_returned_sync_out_doc_view(request):
"""
Show documentation about ballotReturnedSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_returned_sync_out_doc.ballot_returned_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidate_retrieve_doc_view(request):
"""
Show documentation about candidateRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidate_retrieve_doc.candidate_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_retrieve_doc.candidates_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_sync_out_doc_view(request):
"""
Show documentation about candidatesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_sync_out_doc.candidates_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def device_id_generate_doc_view(request):
"""
Show documentation about deviceIdGenerate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = device_id_generate_doc.device_id_generate_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def donation_with_stripe_doc_view(request):
"""
Show documentation about donationWithStripe
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = donation_with_stripe_doc.donation_with_stripe_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def elections_retrieve_doc_view(request):
"""
Show documentation about electionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = elections_retrieve_doc.elections_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def elections_sync_out_doc_view(request):
"""
Show documentation about electionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = elections_sync_out_doc.elections_sync_out_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_disconnect_doc_view(request):
"""
Show documentation about facebookDisconnect
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_disconnect_doc.facebook_disconnect_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_friends_action_doc_view(request):
"""
Show documentation about facebookFriendsAction
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_friends_action_doc.facebook_friends_action_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_save_to_current_account_doc_view(request):
"""
Show documentation about voterFacebookSaveToCurrentAccount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_facebook_save_to_current_account_doc.voter_facebook_save_to_current_account_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def email_ballot_data_doc_view(request):
"""
Show documentation about emailBallotData
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = email_ballot_data_doc.email_ballot_data_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_email_send_doc_view(request):
"""
Show documentation about friendInvitationByEmailSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_email_send_doc.friend_invitation_by_email_send_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_facebook_send_doc_view(request):
"""
Show documentation about friendInvitationByFacebookSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_facebook_send_doc.friend_invitation_by_facebook_send_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_we_vote_id_send_doc_view(request):
"""
Show documentation about friendInvitationByWeVoteIdSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_we_vote_id_send_doc.friend_invitation_by_we_vote_id_send_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_email_verify_doc_view(request):
"""
Show documentation about friendInvitationByEmailVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_email_verify_doc.friend_invitation_by_email_verify_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_facebook_verify_doc_view(request):
"""
Show documentation about friendInvitationByFacebookVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_facebook_verify_doc.friend_invitation_by_facebook_verify_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invite_response_doc_view(request):
"""
Show documentation about friendInviteResponse
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invite_response_doc.friend_invite_response_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_list_doc_view(request):
"""
Show documentation about friendList
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_list_doc.friend_list_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issue_follow_doc_view(request):
"""
Show documentation about issueFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issue_follow_doc.issue_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_retrieve_doc_view(request):
"""
Show documentation about issuesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_retrieve_doc.issues_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_sync_out_doc_view(request):
"""
Show documentation about issuesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_sync_out_doc.issues_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_linked_to_organization_doc_view(request):
"""
Show Documentation about issuesLinkedToOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_linked_to_organization_doc.issues_linked_to_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_to_link_to_for_organization_doc_view(request):
"""
Show Documentation about issuesToLinkToForOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_to_link_to_for_organization_doc.\
issues_to_link_to_for_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measure_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measure_retrieve_doc.measure_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measures_sync_out_doc_view(request):
"""
Show documentation about measuresSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measures_sync_out_doc.measures_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def office_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = office_retrieve_doc.office_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def offices_sync_out_doc_view(request):
"""
Show documentation about officesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = offices_sync_out_doc.offices_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_count_doc_view(request):
"""
Show documentation about organizationCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_count_doc.organization_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_doc_view(request):
"""
Show documentation about organizationFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_doc.organization_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_followed_retrieve_doc.organizations_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_ignore_doc_view(request):
"""
Show documentation about organizationFollowIgnore
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_ignore_doc.organization_follow_ignore_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_link_to_issue_sync_out_doc_view(request):
"""
Show documentation about organizationLinkToIssueSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_link_to_issue_sync_out_doc.organization_link_to_issue_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_link_to_issue_doc_view(request):
"""
Show documentation about organizationLinkToIssue
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_link_to_issue_doc.organization_link_to_issue_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_stop_following_doc_view(request):
"""
Show documentation about organizationStopFollowing
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_stop_following_doc.organization_stop_following_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_retrieve_doc_view(request):
"""
Show documentation about organizationRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_retrieve_doc.organization_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_save_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_save_doc.organization_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_search_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_search_doc.organization_search_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_sync_out_doc_view(request):
"""
Show documentation about organizationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_sync_out_doc.organizations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_suggestion_tasks_doc_view(request):
"""
Show documentation about organizationSuggestionTasks
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_suggestion_tasks_doc.organization_suggestion_tasks_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_ballot_item_doc_view(request):
"""
Show documentation about positionListForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_ballot_item_doc.position_list_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_opinion_maker_doc_view(request):
"""
Show documentation about positionListForOpinionMaker
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_opinion_maker_doc.position_list_for_opinion_maker_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_voter_doc_view(request):
"""
Show documentation about positionListForVoter
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_voter_doc.position_list_for_voter_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_retrieve_doc_view(request):
"""
Show documentation about positionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_retrieve_doc.position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_save_doc_view(request):
"""
Show documentation about positionSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_save_doc.position_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_oppose_count_for_ballot_item_doc.\
position_oppose_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_support_count_for_ballot_item_doc.\
position_support_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_oppose_count_for_ballot_item_doc.\
position_public_oppose_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_support_count_for_ballot_item_doc.\
position_public_support_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_all_ballot_items_doc_view(request):
"""
Show documentation about positionsCountForAllBallotItems
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_all_ballot_items_doc.positions_count_for_all_ballot_items_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_one_ballot_item_doc_view(request):
"""
Show documentation about positionsCountForOneBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def quick_info_retrieve_doc_view(request):
"""
Show documentation about quickInfoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = quick_info_retrieve_doc.\
quick_info_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def retrieve_issues_to_follow_doc_view(request):
"""
Show documentation about retrieveIssuesToFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = retrieve_issues_to_follow_doc. \
retrieve_issues_to_follow_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def save_analytics_action_doc_view(request):
"""
Show documentation about saveAnalyticsAction
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = save_analytics_action_doc. \
save_analytics_action_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def search_all_doc_view(request):
"""
Show documentation about searchAll
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = search_all_doc.\
search_all_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_identity_retrieve_doc_view(request):
"""
Show documentation about twitterIdentityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_identity_retrieve_doc.twitter_identity_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_start_doc_view(request):
"""
Show documentation about twitterSignInStart
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_sign_in_start_doc.twitter_sign_in_start_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_access_token_doc_view(request):
"""
Show documentation about twitterSignInRequestAccessToken
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_access_token_doc.twitter_sign_in_request_access_token_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_voter_info_doc_view(request):
"""
Show documentation about twitterSignInRequestVoterInfo
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_voter_info_doc.twitter_sign_in_request_voter_info_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_retrieve_doc_view(request):
"""
Show documentation about twitterSignInRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_sign_in_retrieve_doc.twitter_sign_in_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_retrieve_ids_i_follow_doc_view(request):
"""
Show documentation about twitterRetrieveIdsIFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_retrieve_ids_i_follow_doc.twitter_retrieve_ids_i_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_retrieve_doc_view(request):
"""
Show documentation about voterAddressRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_retrieve_doc.voter_address_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_save_doc_view(request):
"""
Show documentation about voterAddressSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_save_doc.voter_address_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_doc.voter_ballot_items_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_from_google_civic_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieveFromGoogleCivic
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_from_google_civic_doc.\
voter_ballot_items_retrieve_from_google_civic_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_list_retrieve_doc_view(request):
"""
Show documentation about voterBallotListRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_list_retrieve_doc.voter_ballot_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_count_doc_view(request):
"""
Show documentation about voterCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_count_doc.voter_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_create_doc_view(request):
"""
Show documentation about voterCreate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_create_doc.voter_create_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_retrieve_doc_view(request):
"""
Show documentation about voterEmailAddressRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_retrieve_doc.voter_email_address_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_save_doc_view(request):
"""
Show documentation about voterEmailAddressSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_save_doc.voter_email_address_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_sign_in_doc_view(request):
"""
Show documentation about voterEmailAddressSignIn
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_sign_in_doc.voter_email_address_sign_in_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_verify_doc_view(request):
"""
Show documentation about voterEmailAddressVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_verify_doc.voter_email_address_verify_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_sign_in_retrieve_doc_view(request):
"""
Show documentation about voterFacebookSignInRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_facebook_sign_in_retrieve_doc.voter_facebook_sign_in_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_sign_in_save_doc_view(request):
"""
Show documentation about voterFacebookSignInSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_facebook_sign_in_save_doc.voter_facebook_sign_in_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_follow_all_organizations_followed_by_organization_doc_view(request):
"""
Show documentation about voterFollowAllOrganizationsFollowedByOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_follow_all_organizations_followed_by_organization_doc.\
voter_follow_all_organizations_followed_by_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id (request)
return render (request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_retrieve_doc_view(request):
"""
Show documentation about voterGuidePossibilityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_retrieve_doc.voter_guide_possibility_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_save_doc_view(request):
"""
Show documentation about voterGuidePossibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_possibility_save_doc.voter_guide_possibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_followed_retrieve_doc.voter_guides_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_followed_by_organization_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_followed_by_organization_retrieve_doc.\
voter_guides_followed_by_organization_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id (request)
return render (request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_followers_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_followers_retrieve_doc.voter_guide_followers_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id (request)
return render (request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_save_doc_view(request):
"""
Show documentation about voterGuideSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_save_doc.voter_guides_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_ignored_retrieve_doc_view(request):
"""
Show documentation about organizationsIgnoredRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_ignored_retrieve_doc.voter_guides_ignored_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_retrieve_doc_view(request):
"""
Show documentation about voterGuidesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_retrieve_doc.voter_guides_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_sync_out_doc_view(request):
"""
Show documentation about voterGuidesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_sync_out_doc.voter_guides_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_to_follow_retrieve_doc_view(request):
"""
Show documentation about voterGuidesToFollowRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_to_follow_retrieve_doc.voter_guides_to_follow_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_upcoming_retrieve_doc_view(request):
"""
Show documentation about voterGuidesUpcomingRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_upcoming_retrieve_doc.voter_guides_upcoming_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_location_retrieve_from_ip_doc_view(request):
"""
Show documentation about voterLocationRetrieveFromIP
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_location_retrieve_from_ip_doc.voter_location_retrieve_from_ip_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_merge_two_accounts_doc_view(request):
"""
Show documentation about voterMergeTwoAccounts
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_merge_two_accounts_doc.voter_merge_two_accounts_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_photo_save_doc_view(request):
"""
Show documentation about voterPhotoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_photo_save_doc.voter_photo_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_off_save_doc_view(request):
"""
Show documentation about voterPositionLikeOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_off_save_doc.voter_position_like_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_on_save_doc_view(request):
"""
Show documentation about voterPositionLikeOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_on_save_doc.voter_position_like_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_like_status_retrieve_doc_view(request):
"""
Show documentation about voterPositionLikeStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_like_status_retrieve_doc.voter_position_like_status_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_split_into_two_accounts_doc_view(request):
"""
Show documentation about voterSplitIntoTwoAccounts
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_split_into_two_accounts_doc.voter_split_into_two_accounts_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def pledge_to_vote_with_voter_guide_doc_view(request):
"""
Show documentation about pledgeToVoteWithVoterGuide
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = pledge_to_vote_with_voter_guide_doc.pledge_to_vote_with_voter_guide_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def politicians_sync_out_doc_view(request):
"""
Show documentation about politiciansSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = politicians_sync_out_doc.politicians_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def polling_locations_sync_out_doc_view(request):
"""
Show documentation about pollingLocationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = polling_locations_sync_out_doc.polling_locations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_like_count_doc_view(request):
"""
Show documentation about positionLikeCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_like_count_doc.position_like_count_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_positions_retrieve_doc_view(request):
"""
Show documentation about voterAllPositionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_positions_retrieve_doc.voter_all_positions_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_bookmarks_status_retrieve_doc_view(request):
"""
Show documentation about voterAllBookmarksStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_bookmarks_status_retrieve_doc.voter_all_bookmarks_status_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_retrieve_doc_view(request):
"""
Show documentation about voterPositionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_retrieve_doc.voter_position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_comment_save_doc_view(request):
"""
Show documentation about voterPositionCommentSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_comment_save_doc.voter_position_comment_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_visibility_save_doc_view(request):
"""
Show documentation about voterPositionVisibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_visibility_save_doc.voter_position_visibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_opposing_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_opposing_save_doc.voter_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_opposing_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_retrieve_doc_view(request):
"""
Show documentation about voterRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_retrieve_doc.voter_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_twitter_save_to_current_account_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_twitter_save_to_current_account_doc.voter_twitter_save_to_current_account_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_supporting_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_supporting_save_doc.voter_stop_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_supporting_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_supporting_save_doc.voter_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_sign_out_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_sign_out_doc.voter_sign_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_off_save_doc_view(request):
"""
Show documentation about voterBookmarkOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_off_save_doc.voter_bookmark_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_on_save_doc_view(request):
"""
Show documentation about voterBookmarkOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_on_save_doc.voter_bookmark_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_status_retrieve_doc_view(request):
"""
Show documentation about voterBookmarkStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_status_retrieve_doc.voter_bookmark_status_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_update_doc_view(request):
"""
Show documentation about voterUpdate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_update_doc.voter_update_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_docs.py",
"copies": "1",
"size": "53318",
"license": "mit",
"hash": 867474051103411000,
"line_mean": 41.0488958991,
"line_max": 127,
"alpha_frac": 0.7268652238,
"autogenerated": false,
"ratio": 3.1463472205830283,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43732124443830284,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_docs.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from apis_v1.documentation_source import \
activity_comment_save_doc, activity_list_retrieve_doc, activity_notice_list_retrieve_doc, activity_post_save_doc,\
all_ballot_items_retrieve_doc, \
analytics_action_sync_out_doc, \
apple_sign_in_save_doc, ballot_item_highlights_retrieve_doc, ballot_item_options_retrieve_doc, \
ballot_item_retrieve_doc, ballot_items_search_retrieve_doc, \
ballot_items_sync_out_doc, ballot_returned_sync_out_doc, \
campaign_follow_doc, campaign_retrieve_doc, campaign_save_doc, \
campaign_supporter_retrieve_doc, campaign_supporter_save_doc, \
campaign_list_retrieve_doc, \
candidate_retrieve_doc, candidates_retrieve_doc, candidate_list_for_upcoming_elections_retrieve_doc, \
candidates_sync_out_doc, candidate_to_office_link_sync_out_doc, device_id_generate_doc, \
device_store_firebase_fcm_token_doc, donation_with_stripe_doc, \
elections_retrieve_doc, elections_sync_out_doc, facebook_disconnect_doc, facebook_friends_action_doc, \
friend_invitation_by_email_send_doc, \
friend_invitation_by_email_verify_doc, friend_invitation_by_we_vote_id_send_doc, \
friend_invitation_by_facebook_send_doc, friend_invitation_by_facebook_verify_doc, \
friend_invitation_information_doc, \
friend_invite_response_doc, friend_list_doc, friend_lists_all_doc, issue_descriptions_retrieve_doc, issue_follow_doc, \
issues_followed_retrieve_doc, issues_retrieve_doc, issues_under_ballot_items_retrieve_doc, issues_sync_out_doc, \
issues_linked_to_organization_doc, issues_to_link_to_for_organization_doc, \
measure_retrieve_doc, measures_sync_out_doc, measure_list_for_upcoming_elections_retrieve_doc, \
office_retrieve_doc, offices_sync_out_doc, organization_analytics_by_voter_doc, \
organization_count_doc, organization_daily_metrics_sync_out_doc, \
organization_election_metrics_sync_out_doc, organizations_followed_retrieve_doc, \
organization_follow_doc, organization_follow_ignore_doc, organization_index_doc, organizations_found_on_url_doc, \
organization_link_to_issue_sync_out_doc, organization_link_to_issue_doc, organization_stop_following_doc, \
organization_stop_ignoring_doc, organization_photos_save_doc, \
organization_retrieve_doc, organization_save_doc, organization_search_doc, organizations_sync_out_doc, \
organization_suggestion_tasks_doc, \
pdf_to_html_doc, \
pledge_to_vote_with_voter_guide_doc, politicians_sync_out_doc, polling_locations_sync_out_doc, \
reaction_like_count_doc, position_list_for_ballot_item_doc, position_list_for_ballot_item_from_friends_doc, \
position_list_for_opinion_maker_doc, \
position_list_for_voter_doc, position_oppose_count_for_ballot_item_doc, \
position_public_oppose_count_for_ballot_item_doc, position_retrieve_doc, position_save_doc, \
positions_sync_out_doc, \
position_public_support_count_for_ballot_item_doc, position_support_count_for_ballot_item_doc, \
positions_count_for_all_ballot_items_doc, positions_count_for_one_ballot_item_doc, \
quick_info_retrieve_doc, retrieve_issues_to_follow_doc, \
save_analytics_action_doc, search_all_doc, shared_item_retrieve_doc, \
shared_item_save_doc, site_configuration_retrieve_doc, \
sitewide_daily_metrics_sync_out_doc, sitewide_election_metrics_sync_out_doc, sitewide_voter_metrics_sync_out_doc, \
twitter_identity_retrieve_doc, \
twitter_sign_in_request_access_token_doc, twitter_sign_in_request_voter_info_doc, twitter_sign_in_retrieve_doc, \
twitter_sign_in_start_doc, twitter_retrieve_ids_i_follow_doc, voter_address_retrieve_doc, voter_address_save_doc, \
voter_all_positions_retrieve_doc, voter_all_bookmarks_status_retrieve_doc, \
voter_ballot_items_retrieve_doc, \
voter_ballot_items_retrieve_from_google_civic_doc, voter_ballot_list_retrieve_doc, \
voter_bookmark_off_save_doc, \
voter_bookmark_on_save_doc, voter_bookmark_status_retrieve_doc, \
voter_count_doc, voter_create_doc, voter_email_address_retrieve_doc, voter_email_address_save_doc, \
voter_email_address_sign_in_doc, voter_email_address_verify_doc, voter_facebook_save_to_current_account_doc, \
voter_facebook_sign_in_retrieve_doc, voter_facebook_sign_in_save_doc, \
voter_follow_all_organizations_followed_by_organization_doc, voter_guide_possibility_highlights_retrieve_doc, \
voter_guide_possibility_retrieve_doc, \
voter_guide_possibility_position_save_doc, voter_guide_possibility_positions_retrieve_doc, \
voter_guide_possibility_save_doc, \
voter_guides_followed_retrieve_doc, voter_guides_followed_by_organization_retrieve_doc, \
voter_guide_followers_retrieve_doc, voter_guide_save_doc, voter_guides_ignored_retrieve_doc, \
voter_guides_retrieve_doc, voter_guides_sync_out_doc, voter_guides_to_follow_retrieve_doc, \
voter_guides_from_friends_upcoming_retrieve_doc, voter_guides_upcoming_retrieve_doc, \
voter_location_retrieve_from_ip_doc, voter_merge_two_accounts_doc, \
voter_notification_settings_update_doc, voter_photo_save_doc, \
voter_plan_list_retrieve_doc, voter_plan_save_doc, \
voter_reaction_like_off_save_doc, voter_reaction_like_on_save_doc, reaction_like_status_retrieve_doc, \
voter_position_comment_save_doc, voter_position_retrieve_doc, voter_position_visibility_save_doc, \
voter_opposing_save_doc, voter_retrieve_doc, voter_send_google_contacts_doc, voter_sign_out_doc, \
voter_sms_phone_number_retrieve_doc, voter_sms_phone_number_save_doc, \
voter_split_into_two_accounts_doc, \
voter_stop_opposing_save_doc, \
voter_stop_supporting_save_doc, voter_supporting_save_doc, voter_twitter_save_to_current_account_doc, \
voter_update_doc, voter_verify_secret_code_doc, email_ballot_data_doc
from config.base import get_environment_variable
from django.contrib.messages import get_messages
from django.shortcuts import render
from voter.models import voter_setup
from wevote_functions.functions import get_voter_api_device_id, set_voter_api_device_id, positive_value_exists
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def activity_comment_save_doc_view(request):
"""
Show documentation about activityCommentSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = activity_comment_save_doc.activity_comment_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def activity_list_retrieve_doc_view(request):
"""
Show documentation about activityListRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = activity_list_retrieve_doc.activity_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def activity_notice_list_retrieve_doc_view(request):
"""
Show documentation about activityNoticeListRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = activity_notice_list_retrieve_doc.activity_notice_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def activity_post_save_doc_view(request):
"""
Show documentation about activityPostSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = activity_post_save_doc.activity_post_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def apis_index_doc_view(request):
"""
Show a list of available APIs
"""
# Create a voter_device_id and voter in the database if one doesn't exist yet
results = voter_setup(request)
voter_api_device_id = results['voter_api_device_id']
store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']
messages_on_stage = get_messages(request)
template_values = {
'next': next,
'messages_on_stage': messages_on_stage,
}
response = render(request, 'apis_v1/apis_index.html', template_values)
# We want to store the voter_device_id cookie if it is new
if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
set_voter_api_device_id(request, response, voter_api_device_id)
return response
def all_ballot_items_retrieve_doc_view(request):
"""
Show documentation about allBallotItemsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = all_ballot_items_retrieve_doc.all_ballot_items_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def analytics_action_sync_out_doc_view(request):
"""
Show documentation about analyticsActionSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = analytics_action_sync_out_doc.analytics_action_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_item_highlights_retrieve_doc_view(request):
"""
Show documentation about ballotItemHighlightsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_highlights_retrieve_doc.ballot_item_highlights_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_item_options_retrieve_doc_view(request):
"""
Show documentation about ballotItemOptionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_options_retrieve_doc.ballot_item_options_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_item_retrieve_doc_view(request):
"""
Show documentation about ballotItemRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_item_retrieve_doc.ballot_item_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_items_search_retrieve_doc_view(request):
"""
Show documentation about ballotItemsSearchRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_items_search_retrieve_doc.ballot_items_search_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_items_sync_out_doc_view(request):
"""
Show documentation about ballotItemsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_items_sync_out_doc.ballot_items_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def ballot_returned_sync_out_doc_view(request):
"""
Show documentation about ballotReturnedSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = ballot_returned_sync_out_doc.ballot_returned_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_follow_doc_view(request):
"""
Show documentation about campaignFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_follow_doc.campaign_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_list_retrieve_doc_view(request):
"""
Show documentation about campaignListRetrieve (No CDN)
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_list_retrieve_doc.campaign_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_retrieve_doc_view(request):
"""
Show documentation about campaignRetrieve (CDN) & campaignRetrieveAsOwner (No CDN)
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_retrieve_doc.campaign_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_save_doc_view(request):
"""
Show documentation about campaignSave & campaignStartSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_save_doc.campaign_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_supporter_retrieve_doc_view(request):
"""
Show documentation about campaignSupporterRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_supporter_retrieve_doc.campaign_supporter_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def campaign_supporter_save_doc_view(request):
"""
Show documentation about campaignSupporterSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = campaign_supporter_save_doc.campaign_supporter_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidate_retrieve_doc_view(request):
"""
Show documentation about candidateRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidate_retrieve_doc.candidate_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidate_list_for_upcoming_elections_retrieve_doc_view(request):
"""
Show documentation about candidateListForUpcomingElectionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
candidate_list_for_upcoming_elections_retrieve_doc.doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_retrieve_doc.candidates_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidates_sync_out_doc_view(request):
"""
Show documentation about candidatesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = candidates_sync_out_doc.candidates_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def candidate_to_office_link_sync_out_doc_view(request):
"""
Show documentation about candidateToOfficeLinkSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
candidate_to_office_link_sync_out_doc.candidate_to_office_link_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def device_id_generate_doc_view(request):
"""
Show documentation about deviceIdGenerate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = device_id_generate_doc.device_id_generate_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def device_store_firebase_fcm_token_doc_view(request):
"""
Show documentation about deviceStoreFirebaseCloudMessagingToken
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = device_store_firebase_fcm_token_doc.device_store_firebase_fcm_token_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def donation_with_stripe_doc_view(request):
"""
Show documentation about donationWithStripe
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = donation_with_stripe_doc.donation_with_stripe_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def elections_retrieve_doc_view(request):
"""
Show documentation about electionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = elections_retrieve_doc.elections_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def elections_sync_out_doc_view(request):
"""
Show documentation about electionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = elections_sync_out_doc.elections_sync_out_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_disconnect_doc_view(request):
"""
Show documentation about facebookDisconnect
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_disconnect_doc.facebook_disconnect_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def facebook_friends_action_doc_view(request):
"""
Show documentation about facebookFriendsAction
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = facebook_friends_action_doc.facebook_friends_action_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_save_to_current_account_doc_view(request):
"""
Show documentation about voterFacebookSaveToCurrentAccount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_facebook_save_to_current_account_doc.voter_facebook_save_to_current_account_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def apple_sign_in_save_doc_view(request):
"""
Show documentation about appleSignInSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
apple_sign_in_save_doc.apple_sign_in_save_doc_view_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def email_ballot_data_doc_view(request):
"""
Show documentation about emailBallotData
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = email_ballot_data_doc.email_ballot_data_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_email_send_doc_view(request):
"""
Show documentation about friendInvitationByEmailSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_email_send_doc.friend_invitation_by_email_send_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_facebook_send_doc_view(request):
"""
Show documentation about friendInvitationByFacebookSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_facebook_send_doc.friend_invitation_by_facebook_send_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_we_vote_id_send_doc_view(request):
"""
Show documentation about friendInvitationByWeVoteIdSend
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_we_vote_id_send_doc.friend_invitation_by_we_vote_id_send_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_email_verify_doc_view(request):
"""
Show documentation about friendInvitationByEmailVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_email_verify_doc.friend_invitation_by_email_verify_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_by_facebook_verify_doc_view(request):
"""
Show documentation about friendInvitationByFacebookVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_by_facebook_verify_doc.friend_invitation_by_facebook_verify_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invitation_information_doc_view(request):
"""
Show documentation about friendInvitationInformation
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invitation_information_doc.friend_invitation_information_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_invite_response_doc_view(request):
"""
Show documentation about friendInviteResponse
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_invite_response_doc.friend_invite_response_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_list_doc_view(request):
"""
Show documentation about friendList
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_list_doc.friend_list_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def friend_lists_all_doc_view(request):
"""
Show documentation about friendList
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = friend_lists_all_doc.friend_lists_all_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issue_follow_doc_view(request):
"""
Show documentation about issueFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issue_follow_doc.issue_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issue_descriptions_retrieve_doc_view(request):
"""
Show documentation about issueDescriptionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issue_descriptions_retrieve_doc.issue_descriptions_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_followed_retrieve_doc_view(request):
"""
Show documentation about issuesFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_followed_retrieve_doc.issues_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_retrieve_doc_view(request):
"""
Show documentation about issuesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_retrieve_doc.issues_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_under_ballot_items_retrieve_doc_view(request):
"""
Show documentation about issuesUnderBallotItemsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_under_ballot_items_retrieve_doc.issues_under_ballot_items_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_sync_out_doc_view(request):
"""
Show documentation about issuesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_sync_out_doc.issues_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_linked_to_organization_doc_view(request):
"""
Show Documentation about issuesLinkedToOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_linked_to_organization_doc.issues_linked_to_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def issues_to_link_to_for_organization_doc_view(request):
"""
Show Documentation about issuesToLinkToForOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = issues_to_link_to_for_organization_doc.\
issues_to_link_to_for_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measure_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measure_retrieve_doc.measure_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measures_sync_out_doc_view(request):
"""
Show documentation about measuresSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = measures_sync_out_doc.measures_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def measure_list_for_upcoming_elections_retrieve_doc_view(request):
"""
Show documentation about measureListForUpcomingElectionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
measure_list_for_upcoming_elections_retrieve_doc.doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def office_retrieve_doc_view(request):
"""
Show documentation about candidatesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = office_retrieve_doc.office_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def offices_sync_out_doc_view(request):
"""
Show documentation about officesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = offices_sync_out_doc.offices_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_analytics_by_voter_doc_view(request):
"""
Show documentation about organizationAnalyticsByVoter
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_analytics_by_voter_doc.organization_analytics_by_voter_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_count_doc_view(request):
"""
Show documentation about organizationCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_count_doc.organization_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_daily_metrics_sync_out_doc_view(request):
"""
Show documentation about organizationDailyMetricsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
organization_daily_metrics_sync_out_doc.organization_daily_metrics_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_election_metrics_sync_out_doc_view(request):
"""
Show documentation about organizationElectionMetricsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
organization_election_metrics_sync_out_doc.organization_election_metrics_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_doc_view(request):
"""
Show documentation about organizationFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_doc.organization_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_followed_retrieve_doc.organizations_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_follow_ignore_doc_view(request):
"""
Show documentation about organizationFollowIgnore
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_follow_ignore_doc.organization_follow_ignore_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_index_doc_view(request):
"""
Show documentation about organizationIndex
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_index_doc.organization_index_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_found_on_url_doc_view(request):
"""
Show documentation about organizationsFoundOnUrl
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_found_on_url_doc.organizations_found_on_url_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_link_to_issue_sync_out_doc_view(request):
"""
Show documentation about organizationLinkToIssueSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_link_to_issue_sync_out_doc.organization_link_to_issue_sync_out_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_link_to_issue_doc_view(request):
"""
Show documentation about organizationLinkToIssue
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_link_to_issue_doc.organization_link_to_issue_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_stop_following_doc_view(request):
"""
Show documentation about organizationStopFollowing
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_stop_following_doc.organization_stop_following_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_stop_ignoring_doc_view(request):
"""
Show documentation about organizationStopIgnoring
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_stop_ignoring_doc.organization_stop_ignoring_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_photos_save_doc_view(request):
"""
Show documentation about organizationPhotosSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_photos_save_doc.organization_photos_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_retrieve_doc_view(request):
"""
Show documentation about organizationRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_retrieve_doc.organization_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_save_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_save_doc.organization_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_search_doc_view(request):
"""
Show documentation about organizationSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_search_doc.organization_search_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organizations_sync_out_doc_view(request):
"""
Show documentation about organizationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organizations_sync_out_doc.organizations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def organization_suggestion_tasks_doc_view(request):
"""
Show documentation about organizationSuggestionTasks
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = organization_suggestion_tasks_doc.organization_suggestion_tasks_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_ballot_item_doc_view(request):
"""
Show documentation about positionListForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_ballot_item_doc.position_list_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_ballot_item_from_friends_doc_view(request):
"""
Show documentation about positionListForBallotItemFromFriends
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
position_list_for_ballot_item_from_friends_doc.position_list_for_ballot_item_from_friends_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_opinion_maker_doc_view(request):
"""
Show documentation about positionListForOpinionMaker
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_opinion_maker_doc.position_list_for_opinion_maker_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_list_for_voter_doc_view(request):
"""
Show documentation about positionListForVoter
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_list_for_voter_doc.position_list_for_voter_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_retrieve_doc_view(request):
"""
Show documentation about positionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_retrieve_doc.position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_save_doc_view(request):
"""
Show documentation about positionSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_save_doc.position_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_oppose_count_for_ballot_item_doc.\
position_oppose_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_support_count_for_ballot_item_doc.\
position_support_count_for_ballot_item_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_oppose_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicOpposeCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_oppose_count_for_ballot_item_doc.\
position_public_oppose_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def position_public_support_count_for_ballot_item_doc_view(request):
"""
Show documentation about positionPublicSupportCountForBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = position_public_support_count_for_ballot_item_doc.\
position_public_support_count_for_ballot_item_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_all_ballot_items_doc_view(request):
"""
Show documentation about positionsCountForAllBallotItems
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_all_ballot_items_doc.positions_count_for_all_ballot_items_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_count_for_one_ballot_item_doc_view(request):
"""
Show documentation about positionsCountForOneBallotItem
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_count_for_one_ballot_item_doc.positions_count_for_one_ballot_item_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def positions_sync_out_doc_view(request):
"""
Show documentation about positionsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = positions_sync_out_doc.positions_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def quick_info_retrieve_doc_view(request):
"""
Show documentation about quickInfoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = quick_info_retrieve_doc.\
quick_info_retrieve_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def retrieve_issues_to_follow_doc_view(request):
"""
Show documentation about retrieveIssuesToFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = retrieve_issues_to_follow_doc. \
retrieve_issues_to_follow_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def save_analytics_action_doc_view(request):
"""
Show documentation about saveAnalyticsAction
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = save_analytics_action_doc. \
save_analytics_action_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def search_all_doc_view(request):
"""
Show documentation about searchAll
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = search_all_doc.\
search_all_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def shared_item_retrieve_doc_view(request):
"""
Show documentation about sharedItemRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = shared_item_retrieve_doc.shared_item_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def shared_item_save_doc_view(request):
"""
Show documentation about sharedItemSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = shared_item_save_doc.shared_item_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def site_configuration_retrieve_doc_view(request):
"""
Show documentation about siteConfigurationRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = site_configuration_retrieve_doc.site_configuration_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def sitewide_daily_metrics_sync_out_doc_view(request):
"""
Show documentation about sitewideDailyMetricsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
sitewide_daily_metrics_sync_out_doc.sitewide_daily_metrics_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def sitewide_election_metrics_sync_out_doc_view(request):
"""
Show documentation about sitewideElectionMetricsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
sitewide_election_metrics_sync_out_doc.sitewide_election_metrics_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def sitewide_voter_metrics_sync_out_doc_view(request):
"""
Show documentation about sitewideVoterMetricsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
sitewide_voter_metrics_sync_out_doc.sitewide_voter_metrics_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_identity_retrieve_doc_view(request):
"""
Show documentation about twitterIdentityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_identity_retrieve_doc.twitter_identity_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_start_doc_view(request):
"""
Show documentation about twitterSignInStart
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_sign_in_start_doc.twitter_sign_in_start_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_access_token_doc_view(request):
"""
Show documentation about twitterSignInRequestAccessToken
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_access_token_doc.twitter_sign_in_request_access_token_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_request_voter_info_doc_view(request):
"""
Show documentation about twitterSignInRequestVoterInfo
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
twitter_sign_in_request_voter_info_doc.twitter_sign_in_request_voter_info_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_sign_in_retrieve_doc_view(request):
"""
Show documentation about twitterSignInRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_sign_in_retrieve_doc.twitter_sign_in_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def twitter_retrieve_ids_i_follow_doc_view(request):
"""
Show documentation about twitterRetrieveIdsIFollow
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = twitter_retrieve_ids_i_follow_doc.twitter_retrieve_ids_i_follow_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_retrieve_doc_view(request):
"""
Show documentation about voterAddressRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_retrieve_doc.voter_address_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_address_save_doc_view(request):
"""
Show documentation about voterAddressSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_address_save_doc.voter_address_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_doc.voter_ballot_items_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_items_retrieve_from_google_civic_doc_view(request):
"""
Show documentation about voterBallotItemsRetrieveFromGoogleCivic
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_items_retrieve_from_google_civic_doc.\
voter_ballot_items_retrieve_from_google_civic_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_ballot_list_retrieve_doc_view(request):
"""
Show documentation about voterBallotListRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_ballot_list_retrieve_doc.voter_ballot_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_count_doc_view(request):
"""
Show documentation about voterCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_count_doc.voter_count_doc_template_values(url_root)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_create_doc_view(request):
"""
Show documentation about voterCreate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_create_doc.voter_create_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_retrieve_doc_view(request):
"""
Show documentation about voterEmailAddressRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_retrieve_doc.voter_email_address_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_save_doc_view(request):
"""
Show documentation about voterEmailAddressSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_save_doc.voter_email_address_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_sign_in_doc_view(request):
"""
Show documentation about voterEmailAddressSignIn
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_sign_in_doc.voter_email_address_sign_in_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_email_address_verify_doc_view(request):
"""
Show documentation about voterEmailAddressVerify
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_email_address_verify_doc.voter_email_address_verify_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_sign_in_retrieve_doc_view(request):
"""
Show documentation about voterFacebookSignInRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_facebook_sign_in_retrieve_doc.voter_facebook_sign_in_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_facebook_sign_in_save_doc_view(request):
"""
Show documentation about voterFacebookSignInSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_facebook_sign_in_save_doc.voter_facebook_sign_in_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_follow_all_organizations_followed_by_organization_doc_view(request):
"""
Show documentation about voterFollowAllOrganizationsFollowedByOrganization
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_follow_all_organizations_followed_by_organization_doc.\
voter_follow_all_organizations_followed_by_organization_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_retrieve_doc_view(request):
"""
Show documentation about voterGuidePossibilityRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_retrieve_doc.voter_guide_possibility_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_highlights_retrieve_doc_view(request):
"""
Show documentation about voterGuidePossibilityHighlightsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_highlights_retrieve_doc.voter_guide_possibility_highlights_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_position_save_doc_view(request):
"""
Show documentation about voterGuidePossibilityPositionSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_position_save_doc.voter_guide_possibility_position_save_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_positions_retrieve_doc_view(request):
"""
Show documentation about voterGuidePossibilityPositionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_guide_possibility_positions_retrieve_doc.voter_guide_possibility_positions_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_possibility_save_doc_view(request):
"""
Show documentation about voterGuidePossibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_possibility_save_doc.voter_guide_possibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_followed_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_followed_retrieve_doc.voter_guides_followed_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_followed_by_organization_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_followed_by_organization_retrieve_doc.\
voter_guides_followed_by_organization_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_followers_retrieve_doc_view(request):
"""
Show documentation about organizationsFollowedRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_followers_retrieve_doc.voter_guide_followers_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guide_save_doc_view(request):
"""
Show documentation about voterGuideSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guide_save_doc.voter_guide_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_ignored_retrieve_doc_view(request):
"""
Show documentation about organizationsIgnoredRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_ignored_retrieve_doc.voter_guides_ignored_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_retrieve_doc_view(request):
"""
Show documentation about voterGuidesRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_retrieve_doc.voter_guides_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_sync_out_doc_view(request):
"""
Show documentation about voterGuidesSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_sync_out_doc.voter_guides_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_to_follow_retrieve_doc_view(request):
"""
Show documentation about voterGuidesToFollowRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_to_follow_retrieve_doc.voter_guides_to_follow_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_from_friends_upcoming_retrieve_doc_view(request):
"""
Show documentation about voterGuidesFromFriendsUpcomingRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_from_friends_upcoming_retrieve_doc.\
voter_guides_from_friends_upcoming_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_guides_upcoming_retrieve_doc_view(request):
"""
Show documentation about voterGuidesUpcomingRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_guides_upcoming_retrieve_doc.voter_guides_upcoming_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_location_retrieve_from_ip_doc_view(request):
"""
Show documentation about voterLocationRetrieveFromIP
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_location_retrieve_from_ip_doc.voter_location_retrieve_from_ip_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_merge_two_accounts_doc_view(request):
"""
Show documentation about voterMergeTwoAccounts
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_merge_two_accounts_doc.voter_merge_two_accounts_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_notification_settings_update_doc_view(request):
"""
Show documentation about voterNotificationSettingsUpdate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_notification_settings_update_doc.voter_notification_settings_update_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_photo_save_doc_view(request):
"""
Show documentation about voterPhotoRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_photo_save_doc.voter_photo_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_plan_list_retrieve_doc_view(request):
"""
Show documentation about voterPlanListRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_plan_list_retrieve_doc.voter_plan_list_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_plan_save_doc_view(request):
"""
Show documentation about voterPlanSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_plan_save_doc.voter_plan_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_send_google_contacts_doc_view(request):
"""
Show documentation about voterPlanSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_send_google_contacts_doc.voter_send_google_contacts_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_reaction_like_off_save_doc_view(request):
"""
Show documentation about voterReactionLikeOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_reaction_like_off_save_doc.voter_reaction_like_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_reaction_like_on_save_doc_view(request):
"""
Show documentation about voterReactionLikeOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_reaction_like_on_save_doc.voter_reaction_like_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def reaction_like_status_retrieve_doc_view(request):
"""
Show documentation about reactionLikeStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = reaction_like_status_retrieve_doc.reaction_like_status_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_split_into_two_accounts_doc_view(request):
"""
Show documentation about voterSplitIntoTwoAccounts
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_split_into_two_accounts_doc.voter_split_into_two_accounts_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def pledge_to_vote_with_voter_guide_doc_view(request):
"""
Show documentation about pledgeToVoteWithVoterGuide
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = pledge_to_vote_with_voter_guide_doc.pledge_to_vote_with_voter_guide_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def politicians_sync_out_doc_view(request):
"""
Show documentation about politiciansSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = politicians_sync_out_doc.politicians_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def polling_locations_sync_out_doc_view(request):
"""
Show documentation about pollingLocationsSyncOut
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = polling_locations_sync_out_doc.polling_locations_sync_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def reaction_like_count_doc_view(request):
"""
Show documentation about reactionLikeCount
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = reaction_like_count_doc.reaction_like_count_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_positions_retrieve_doc_view(request):
"""
Show documentation about voterAllPositionsRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_positions_retrieve_doc.voter_all_positions_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_all_bookmarks_status_retrieve_doc_view(request):
"""
Show documentation about voterAllBookmarksStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_all_bookmarks_status_retrieve_doc.voter_all_bookmarks_status_retrieve_doc_template_values(
url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_retrieve_doc_view(request):
"""
Show documentation about voterPositionRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_retrieve_doc.voter_position_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_comment_save_doc_view(request):
"""
Show documentation about voterPositionCommentSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_comment_save_doc.voter_position_comment_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_position_visibility_save_doc_view(request):
"""
Show documentation about voterPositionVisibilitySave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_position_visibility_save_doc.voter_position_visibility_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_opposing_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_opposing_save_doc.voter_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_opposing_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_retrieve_doc_view(request):
"""
Show documentation about voterRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_retrieve_doc.voter_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_twitter_save_to_current_account_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = \
voter_twitter_save_to_current_account_doc.voter_twitter_save_to_current_account_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_stop_supporting_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_supporting_save_doc.voter_stop_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_supporting_save_doc_view(request):
"""
Show documentation about voterSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_supporting_save_doc.voter_supporting_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_sign_out_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_sign_out_doc.voter_sign_out_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_sms_phone_number_retrieve_doc_view(request):
"""
Show documentation about voterSMSPhoneNumberRetrieve
:param request:
:return:
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_sms_phone_number_retrieve_doc.voter_sms_phone_number_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_sms_phone_number_save_doc_view(request):
"""
Show documentation about voterSMSPhoneNumberSave
:param request:
:return:
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_sms_phone_number_save_doc.voter_sms_phone_number_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_off_save_doc_view(request):
"""
Show documentation about voterBookmarkOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_off_save_doc.voter_bookmark_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_on_save_doc_view(request):
"""
Show documentation about voterBookmarkOnSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_on_save_doc.voter_bookmark_on_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_bookmark_status_retrieve_doc_view(request):
"""
Show documentation about voterBookmarkStatusRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_bookmark_status_retrieve_doc.voter_bookmark_status_retrieve_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_verify_secret_code_doc_view(request):
"""
Show documentation about voterVerifySecretCode
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_verify_secret_code_doc.voter_verify_secret_code_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def voter_update_doc_view(request):
"""
Show documentation about voterUpdate
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_update_doc.voter_update_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
def pdf_to_html_retrieve_view(request):
"""
Show documentation about pdfToHtmlRetrieve
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = pdf_to_html_doc.pdf_to_html_retrieve_view(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
return render(request, 'apis_v1/api_doc_page.html', template_values)
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_docs.py",
"copies": "1",
"size": "76395",
"license": "mit",
"hash": 2298719904206964000,
"line_mean": 41.1373414231,
"line_max": 125,
"alpha_frac": 0.7271287388,
"autogenerated": false,
"ratio": 3.1682080205698173,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9389782829685213,
"avg_score": 0.0011107859369208436,
"num_lines": 1813
} |
# apis_v1/views/views_donation.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from stripe_donations.controllers import donation_lists_for_a_voter
from stripe_donations.controllers import donation_active_paid_plan_retrieve, donation_with_stripe_for_api, \
donation_process_stripe_webhook_event, \
donation_refund_for_api, donation_subscription_cancellation_for_api, donation_journal_history_for_a_voter
from stripe_donations.models import StripeManager
import json
from voter.models import fetch_voter_we_vote_id_from_voter_device_link, VoterManager
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
import stripe
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def donation_with_stripe_view(request): # donationWithStripe
"""
Make a charge with a stripe token. This could either be:
A) one-time or monthly donation
B) payment for a subscription plan
:type request: object
:param request:
:return:
"""
token = request.GET.get('token', '')
client_ip = request.GET.get('client_ip', '')
payment_method_id = request.GET.get('payment_method_id', '')
email = request.GET.get('email', '')
donation_amount = request.GET.get('donation_amount', 0)
monthly_donation = positive_value_exists(request.GET.get('monthly_donation', False))
is_organization_plan = positive_value_exists(request.GET.get('is_organization_plan', False))
coupon_code = request.GET.get('coupon_code', '')
plan_type_enum = request.GET.get('plan_type_enum', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
else:
logger.error('%s', 'donation_with_stripe_view voter_we_vote_id is missing')
voter_manager = VoterManager()
linked_organization_we_vote_id = \
voter_manager.fetch_linked_organization_we_vote_id_by_voter_we_vote_id(voter_we_vote_id)
if positive_value_exists(token):
results = donation_with_stripe_for_api(request, token, payment_method_id, client_ip, email, donation_amount,
monthly_donation, voter_we_vote_id, is_organization_plan, coupon_code,
plan_type_enum, linked_organization_we_vote_id)
org_subs_already_exists = results['org_subs_already_exists'] if \
'org_subs_already_exists' in results else False
active_results = donation_active_paid_plan_retrieve(linked_organization_we_vote_id, voter_we_vote_id)
active_paid_plan = active_results['active_paid_plan']
# donation_plan_definition_list_json = active_results['donation_plan_definition_list_json']
donation_subscription_list, donation_payments_list = donation_lists_for_a_voter(voter_we_vote_id)
json_data = {
'status': results['status'],
'success': results['success'],
'active_paid_plan': active_paid_plan,
'amount_paid': results['amount_paid'],
'charge_id': results['charge_id'],
'stripe_customer_id': results['stripe_customer_id'],
'donation_subscription_list': donation_subscription_list,
'donation_payments_list': donation_payments_list,
'error_message_for_voter': results['error_message_for_voter'],
'stripe_failure_code': results['stripe_failure_code'],
'monthly_donation': monthly_donation,
'organization_saved': results['organization_saved'],
'org_subs_already_exists': org_subs_already_exists,
'plan_type_enum': results['plan_type_enum'],
'saved_donation_in_log': results['donation_entry_saved'],
'saved_stripe_donation': results['saved_stripe_donation'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
json_data = {
'status': "TOKEN_IS_MISSING ",
'success': False,
'amount_paid': 0,
'error_message_for_voter': 'Cannot connect to payment processor.',
'organization_saved': False,
'plan_type_enum': '',
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def donation_refund_view(request): # donationRefund
"""
Refund a stripe charge
:type request: object
:param request:
:return:
"""
charge_id = request.GET.get('charge', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if len(charge_id) > 1:
results = donation_refund_for_api(request, charge_id, voter_we_vote_id)
json_data = {
'success': str(results),
'charge_id': charge_id,
'donation_list': donation_journal_history_for_a_voter(voter_we_vote_id),
'voter_we_vote_id': voter_we_vote_id,
}
else:
logger.error('%s', 'donation_refund_view voter_we_vote_id is missing')
json_data = {
'status': "VOTER_WE_VOTE_ID_IS_MISSING",
'success': False,
}
else:
logger.error('%s', 'donation_refund_view stripe_charge_id is missing')
json_data = {
'status': "STRIPE_CHARGE_ID_IS_MISSING",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def donation_cancel_subscription_view(request): # donationCancelSubscription
"""
Cancel a stripe subscription or subscription plan
:type request: object
:param request:
:return:
"""
plan_type_enum = request.GET.get('plan_type_enum', '')
stripe_subscription_id = request.GET.get('stripe_subscription_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if len(voter_we_vote_id) > 0:
json_data = donation_subscription_cancellation_for_api(
voter_we_vote_id, plan_type_enum=plan_type_enum, stripe_subscription_id=stripe_subscription_id)
else:
logger.error('%s', 'donation_cancel_subscription_view voter_we_vote_id is missing')
json_data = {
'status': "VOTER_WE_VOTE_ID_IS_MISSING ",
'success': False,
}
else:
logger.error('%s', 'donation_cancel_subscription_view stripe_subscription_id is missing')
json_data = {
'status': "STRIPE_SUBSCRIPTION_ID_IS_MISSING ",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# Using ngrok to test Stripe Webhook
# https://a9a761d9.ngrok.io/apis/v1/donationStripeWebhook/
# http://a9a761d9.ngrok.io -> localhost:8000
# Important!!!!!!! django urls without a trailing slash do not redirect !!!!!!
# The webhook in the stripe console HAS TO END WITH A '/' or you are doomed to waste a bunch of time!
@csrf_exempt
def donation_stripe_webhook_view(request):
# print('first line in donation_stripe_webhook')
payload = request.body.decode('utf-8')
try:
stripe.api_key = get_environment_variable("STRIPE_SECRET_KEY")
event = stripe.Event.construct_from(json.loads(payload), stripe.api_key)
except ValueError as e:
logger.error("donation_stripe_webhook_view, Stripe returned ValueError: " + str(e))
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as err:
logger.error("donation_stripe_webhook_view, Stripe returned SignatureVerificationError: " + str(err))
return HttpResponse(status=400)
except Exception as err:
logger.error("donation_stripe_webhook_view: " + str(err))
return HttpResponse(status=400)
donation_process_stripe_webhook_event(event)
return HttpResponse(status=200)
def donation_history_list_view(request): # donationHistory
"""
Get the donor history list for a voter
:type request: object
:param request:
:return:
"""
stripe_subscription_id = request.GET.get('stripe_subscription_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
status = ""
active_paid_plan = {
'last_amount_paid': 0,
'plan_type_enum': '',
'subscription_active': False,
'subscription_canceled_at': '',
'subscription_ended_at': '',
'stripe_subscription_id': stripe_subscription_id,
}
donation_subscription_list = []
donation_payments_list = []
if positive_value_exists(voter_device_id):
voter_manager = VoterManager()
results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
if not results['voter_found']:
logger.error("donation_history_list received invalid voter_device_id: " + voter_device_id)
status += "DONATION_HISTORY_LIST-INVALID_VOTER_DEVICE_ID_PASSED "
success = False
else:
success = True
voter = results['voter']
voter_we_vote_id = voter.we_vote_id
linked_organization_we_vote_id = voter.linked_organization_we_vote_id
donation_subscription_list, donation_payments_list = donation_lists_for_a_voter(voter_we_vote_id)
active_results = donation_active_paid_plan_retrieve(linked_organization_we_vote_id, voter_we_vote_id)
active_paid_plan = active_results['active_paid_plan']
json_data = {
'active_paid_plan': active_paid_plan,
'donation_subscription_list': donation_subscription_list,
'donation_payments_list': donation_payments_list,
'status': status,
'success': success,
}
else:
logger.error('%s', 'donation_history_list stripe_subscription_id is missing')
json_data = {
'active_paid_plan': active_paid_plan,
'donation_list': [],
'donation_plan_definition_list': [],
'status': "DONATION_HISTORY_LIST-STRIPE_SUBSCRIPTION_ID_IS_MISSING",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# def coupon_summary_retrieve_for_api_view(request): # couponSummaryRetrieve
# coupon_code = request.GET.get('coupon_code', '')
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
#
# if positive_value_exists(voter_device_id):
# voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
# json_data = DonationManager.retrieve_coupon_summary(coupon_code)
# else:
# json_data = {
# 'success': False,
# 'status': "coupon_summary_retrieve_for_api_view received bad voter_device_id",
# }
#
# return HttpResponse(json.dumps(json_data), content_type='application/json')
#
#
# def default_pricing_for_api_view(request): # defaultPricing
# json_data = DonationManager.retrieve_default_pricing()
#
# return HttpResponse(json.dumps(json_data), content_type='application/json')
#
#
# def validate_coupon_for_api_view(request): # validateCoupon
# plan_type_enum = request.GET.get('plan_type_enum', '')
# coupon_code = request.GET.get('coupon_code', '')
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# print("validate_coupon_for_api_view, plan_type_enum: " + plan_type_enum + ", coupon_code: " + coupon_code)
#
# if positive_value_exists(voter_device_id):
# voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
# json_data = DonationManager.validate_coupon(plan_type_enum, coupon_code)
# else:
# json_data = {
# 'success': False,
# 'status': "validate_coupon_for_api_view received bad voter_device_id",
# }
#
# return HttpResponse(json.dumps(json_data), content_type='application/json')
#
#
# def create_new_plan_for_api_view(request):
# authority_required = {'admin'}
# if not voter_has_authority(request, authority_required):
# return redirect_to_sign_in_page(request, authority_required)
#
# coupon_code = request.GET.get('couponCode')
# plan_type_enum = request.GET.get('planTypeEnum')
# hidden_plan_comment = request.GET.get('hiddenPlanComment')
# coupon_applied_message = request.GET.get('couponAppliedMessage')
# monthly_price_stripe = request.GET.get('monthlyPriceStripe')
# monthly_price_stripe = monthly_price_stripe if monthly_price_stripe != '' else 0
# annual_price_stripe = request.GET.get('annualPriceStripe')
# annual_price_stripe = annual_price_stripe if annual_price_stripe != '' else 0
# master_feature_package = request.GET.get('masterFeatureType')
# features_provided_bitmap = request.GET.get('featuresProvidedBitmap')
# coupon_expires_date = request.GET.get('couponExpiresDate', None)
# if len(coupon_expires_date) == 0:
# coupon_expires_date = None
# print("create_new_plan_for_api_view, plan_type_enum: " + plan_type_enum + ", coupon_code: " + coupon_code)
# plan_on_stage = 0
#
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# if positive_value_exists(voter_device_id):
# voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
# plan_on_stage = OrganizationSubscriptionPlans.objects.create(
# coupon_code=coupon_code,
# plan_type_enum=plan_type_enum,
# hidden_plan_comment=hidden_plan_comment,
# coupon_applied_message=coupon_applied_message,
# monthly_price_stripe=monthly_price_stripe,
# annual_price_stripe=annual_price_stripe,
# master_feature_package=master_feature_package,
# features_provided_bitmap=features_provided_bitmap,
# coupon_expires_date=coupon_expires_date)
# status = "create_new_plan_for_api_view succeeded"
# else:
# status = "create_new_plan_for_api_view received bad voter_device_id",
#
# json_data = {
# 'success': positive_value_exists(plan_on_stage.id),
# 'status': status,
# 'id': plan_on_stage.id if positive_value_exists(plan_on_stage.id) else 0.
# }
#
# return HttpResponse(json.dumps(json_data), content_type='application/json')
#
#
# def delete_plan_for_api_view(request):
# authority_required = {'admin'}
# if not voter_has_authority(request, authority_required):
# return redirect_to_sign_in_page(request, authority_required)
#
# id = request.GET.get('id')
# print("delete_coupon_for_api_view, sql id: " + id)
#
# try:
# if positive_value_exists(id):
# OrganizationSubscriptionPlans.objects.filter(id=id).delete()
# status = "DELETE_PLAN_SUCCESSFUL"
# success = True
# else:
# status = "DELETE_PLAN-MISSING_ID"
# success = False
# except Exception as e:
# status = "DELETE_PLAN-DATABASE_DELETE_EXCEPTION"
# success = False
#
# json_data = {
# 'success': success,
# 'status': status,
# 'id': id,
# }
#
# return HttpResponse(json.dumps(json_data), content_type='application/json')
def does_paid_subscription_exist_for_api(request): # doesOrgHavePaidPlan
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
else:
logger.error('%s', 'donation_with_stripe_view voter_we_vote_id is missing')
voter_manager = VoterManager()
organization_we_vote_id = voter_manager.fetch_linked_organization_we_vote_id_by_voter_we_vote_id(voter_we_vote_id)
found_live_paid_subscription_for_the_org = StripeManager.does_paid_subscription_exist(organization_we_vote_id)
json_data = {
'org_has_active_paid_plan': found_live_paid_subscription_for_the_org,
'success': True,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_donation.py",
"copies": "1",
"size": "17165",
"license": "mit",
"hash": -4381624226390850600,
"line_mean": 42.7882653061,
"line_max": 118,
"alpha_frac": 0.6415962715,
"autogenerated": false,
"ratio": 3.3796022839141564,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45211985554141565,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_donaton.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
from donate.controllers import donation_with_stripe_for_api, donation_process_stripe_webhook_event, \
donation_refund_for_api, donation_subscription_cancellation_for_api
import json
from voter.models import fetch_voter_we_vote_id_from_voter_device_link
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
import stripe
from django.views.decorators.csrf import csrf_exempt
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def donation_with_stripe_view(request): # donationWithStripe
"""
Make a charge with a stripe token
:type request: object
:param request:
:return:
"""
token = request.GET.get('token', '')
email = request.GET.get('email', '')
donation_amount = request.GET.get('donation_amount', 0)
monthly_donation = positive_value_exists(request.GET.get('monthly_donation', False))
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
else:
print('view voter_we_vote_id is missing')
if positive_value_exists(token):
results = donation_with_stripe_for_api(request, token, email, donation_amount, monthly_donation,
voter_we_vote_id)
json_data = {
'status': results['status'],
'success': results['success'],
'charge_id': results['charge_id'],
'customer_id': results['customer_id'],
'saved_donation_in_log': results['donation_entry_saved'],
'saved_stripe_donation': results['saved_stripe_donation'],
'monthly_donation': monthly_donation,
'subscription': results['subscription'],
'error_message_for_voter': results['error_message_for_voter']
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
json_data = {
'status': "TOKEN_IS_MISSING",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def donation_refund_view(request): # donationRefund
"""
Refund a stripe charge
:type request: object
:param request:
:return:
"""
charge_id = request.GET.get('charge', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if len(charge_id) > 1:
results = donation_refund_for_api(request, charge_id, voter_we_vote_id)
json_data = {
'success': str(results),
'charge_id': charge_id,
'voter_we_vote_id': voter_we_vote_id,
}
else :
print('donation_refund_view voter_we_vote_id is missing')
json_data = {
'status': "VOTER_WE_VOTE_ID_IS_MISSING",
'success': False,
}
else :
print('donation_refund_view stripe_charge_id is missing')
json_data = {
'status': "STRIPE_CHARGE_ID_IS_MISSING",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def donation_cancel_subscription_view(request): # donationCancelSubscription
"""
Cancel a stripe subscription
:type request: object
:param request:
:return:
"""
subscription_id = request.GET.get('subscription_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if len(subscription_id) > 0:
json_data = donation_subscription_cancellation_for_api(request, subscription_id, voter_we_vote_id)
else:
print('donation_subscription_cancellation_with_stripe_view voter_we_vote_id is missing')
json_data = {
'status': "VOTER_WE_VOTE_ID_IS_MISSING",
'success': False,
}
else:
print('donation_subscription_cancellation_with_stripe_view stripe_subscription_id is missing')
json_data = {
'status': "STRIPE_SUBSCRIPTION_ID_IS_MISSING",
'success': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# Using ngrok to test Stripe Webhook
# https://a9a761d9.ngrok.io/apis/v1/donationStripeWebhook/
# http://a9a761d9.ngrok.io -> localhost:8000
@csrf_exempt
def donation_stripe_webhook_view(request):
payload = request.body.decode('utf-8')
if 'HTTP_STRIPE_SIGNATURE' in request.META:
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
else:
sig_header = ""
endpoint_secret = get_environment_variable("STRIPE_SIGNING_SECRET")
try:
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
except ValueError as e:
logger.error("donation_stripe_webhook_view, Stripe returned 'Invalid payload'")
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as err:
logger.error("donation_stripe_webhook_view, Stripe returned SignatureVerificationError: " + str(err))
return HttpResponse(status=400)
except Exception as err:
logger.error("donation_stripe_webhook_view: " + str(err))
return HttpResponse(status=400)
donation_process_stripe_webhook_event(event)
return HttpResponse(status=200)
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_donation.py",
"copies": "1",
"size": "6079",
"license": "mit",
"hash": 6366485263024015000,
"line_mean": 36.2944785276,
"line_max": 110,
"alpha_frac": 0.6451719033,
"autogenerated": false,
"ratio": 3.522016222479722,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4667188125779722,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_election.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
from election.controllers import elections_retrieve_for_api, elections_sync_out_list_for_api
import json
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def elections_retrieve_view(request): # electionsRetrieve
"""
:param request:
:return:
"""
results = elections_retrieve_for_api()
json_data = {
'status': results['status'],
'success': results['success'],
'election_list': results['election_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def elections_sync_out_view(request): # electionsSyncOut
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = elections_sync_out_list_for_api(voter_device_id)
if 'success' not in results:
json_data = results['json_data']
return HttpResponse(json.dumps(json_data), content_type='application/json')
elif not results['success']:
json_data = results['json_data']
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
election_list = results['election_list']
election_list_dict = election_list.values(
'ballotpedia_election_id', 'ballotpedia_kind_of_election', 'candidate_photos_finished', 'ctcl_uuid',
'election_day_text', 'election_name', 'election_preparation_finished',
'google_civic_election_id', 'ignore_this_election', 'include_in_list_for_voters', 'internal_notes',
'is_national_election', 'ocd_division_id', 'state_code', 'use_ballotpedia_as_data_source',
'use_ctcl_as_data_source', 'use_google_civic_as_data_source', 'use_vote_usa_as_data_source')
if election_list_dict:
election_list_json = list(election_list_dict)
return HttpResponse(json.dumps(election_list_json), content_type='application/json')
else:
json_data = {
'success': False,
'status': 'ELECTION_LIST_MISSING',
'voter_device_id': voter_device_id
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_election.py",
"copies": "1",
"size": "2601",
"license": "mit",
"hash": 7318285440672759000,
"line_mean": 43.8448275862,
"line_max": 112,
"alpha_frac": 0.6574394464,
"autogenerated": false,
"ratio": 3.477272727272727,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4634712173672727,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_extension.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import boto3
import datetime
import json
import os
import subprocess
import urllib.request
from django.http import HttpResponse
import wevote_functions.admin
from config.base import get_environment_variable
from wevote_functions.functions import positive_value_exists, get_voter_device_id
from exception.models import handle_exception
AWS_ACCESS_KEY_ID = get_environment_variable("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_environment_variable("AWS_SECRET_ACCESS_KEY")
AWS_REGION_NAME = get_environment_variable("AWS_REGION_NAME")
AWS_STORAGE_BUCKET_NAME = "wevote-temporary"
AWS_STORAGE_SERVICE = "s3"
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def pdf_to_html_retrieve_view(request): # pdfToHtmlRetrieve
"""
return a URL to a s3 file that contains the html rough equivalent of the PDF
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
pdf_url = request.GET.get('pdf_url', '')
if not positive_value_exists(pdf_url):
status = 'PDF_URL_MISSING'
json_data = {
'status': status,
'success': False,
's3_url_for_html': '',
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
json_data = process_pdf_to_html(pdf_url)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def process_pdf_to_html(pdf_url):
file_name, headers = urllib.request.urlretrieve(pdf_url)
pdf_name = os.path.basename(pdf_url)
dirname, basename = os.path.split(file_name)
temp_file_name = file_name.replace(basename, pdf_name)
try:
os.remove(temp_file_name)
html_name = temp_file_name.replace('.pdf', '.html')
os.remove(html_name)
except Exception:
pass
os.rename(file_name, temp_file_name)
# https://github.com/pdf2htmlEX/pdf2htmlEX !Not the abandoned coolwanglu original branch!
# https://github.com/pdf2htmlEX/pdf2htmlEX/wiki/Command-Line-Options
# In December 2020, we installed a docker image in AWS/EC2: https://hub.docker.com/r/cardboardci/pdf2htmlex
# pdf2htmlEX -zoom 1.3 Cook-18-Primary-Web.pdf
# Test cases:
# https://www.iuoe399.org/media/filer_public/45/77/457700c9-dd70-4cfc-be49-a81cb3fba0a6/2020_lu399_primary_endorsement.pdf
# http://www.local150.org/wp-content/uploads/2018/02/Cook-18-Primary-Web.pdf
# http://www.sddemocrats.org/sites/sdcdp/files/pdf/Endorsements_Flyer_P2020b.pdf
# https://crpa.org/wp-content/uploads/2020-CA-Primary-Candidate-Final.pdf
process = subprocess.run(['pdf2htmlEX', '--dest-dir', dirname, temp_file_name])
output = process.stdout
temp_file_name = temp_file_name.replace('.pdf', '.html')
insert_pdf_filename_in_tmp_file(temp_file_name, pdf_url)
s3_url_for_html = store_temporary_html_file_to_aws(temp_file_name)
print("views_extension stored temp html file: ", temp_file_name, s3_url_for_html)
status = 'PDF_URL_RETURNED'
json_data = {
'status': status,
'success': True,
'output_from_subprocess': output,
's3_url_for_html': s3_url_for_html,
}
return json_data
def store_temporary_html_file_to_aws(temp_file_name):
"""
Upload temporary_html_file directly to AWS
:param temp_file_name:
:return:
"""
s3_html_url = ""
try:
head, tail = os.path.split(temp_file_name)
date_in_a_year = datetime.datetime.now() + + datetime.timedelta(days=365)
session = boto3.session.Session(region_name=AWS_REGION_NAME,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
s3 = session.resource(AWS_STORAGE_SERVICE)
s3.Bucket(AWS_STORAGE_BUCKET_NAME).upload_file(
temp_file_name, tail, ExtraArgs={'Expires': date_in_a_year, 'ContentType': 'text/html'})
s3_html_url = "https://{bucket_name}.s3.amazonaws.com/{file_location}" \
"".format(bucket_name=AWS_STORAGE_BUCKET_NAME,
file_location=tail)
except Exception as e:
print(e)
exception_message = "store_temp_html_file_to_aws failed"
handle_exception(e, logger=logger, exception_message=exception_message)
return s3_html_url
def insert_pdf_filename_in_tmp_file(temp_file, pdf_url):
f = open(temp_file, "r")
contents = f.readlines()
f.close()
value = "<input type=\"hidden\" name=\"pdfFileName\" value=\"{pdf_url}\" />\n".format(pdf_url=pdf_url)
# insert the hidden input as the first line of the body -- containgingthe original URL for the PDF
offset = contents.index("<body>\n") + 1
contents.insert(offset, value)
f = open(temp_file, "w")
contents = "".join(contents)
f.write(contents)
f.close()
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_extension.py",
"copies": "1",
"size": "5125",
"license": "mit",
"hash": -5092679917792189000,
"line_mean": 37.2462686567,
"line_max": 126,
"alpha_frac": 0.6565853659,
"autogenerated": false,
"ratio": 3.260178117048346,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4416763482948346,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_facebook.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
from import_export_facebook.controllers import facebook_disconnect_for_api, \
voter_facebook_save_to_current_account_for_api, facebook_friends_action_for_api
import json
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def facebook_friends_action_view(request): # facebookFriendsActions
"""
This is used to retrieve facebook friends who are using WeVote app by facebook 'friends' API.
However we use the Facebook "games" api "invitable_friends" data on the fly from the webapp, to invite facebook
friends who are not using we vote.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = facebook_friends_action_for_api(voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_friend_suggestion_found': results['facebook_friend_suggestion_found'],
'facebook_suggested_friend_count': results['facebook_suggested_friend_count'],
'facebook_friends_using_we_vote_list': results['facebook_friends_using_we_vote_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def facebook_disconnect_view(request):
"""
Disconnect this We Vote account from current Facebook account
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = facebook_disconnect_for_api(voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_facebook_save_to_current_account_view(request): # voterFacebookSaveToCurrentAccount
"""
Saving the results of signing in with Facebook
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_facebook_save_to_current_account_for_api(voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_facebook.py",
"copies": "2",
"size": "2851",
"license": "mit",
"hash": -3950832712307516000,
"line_mean": 40.3188405797,
"line_max": 115,
"alpha_frac": 0.6787092248,
"autogenerated": false,
"ratio": 3.5906801007556677,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0014803032302074766,
"num_lines": 69
} |
# apis_v1/views/views_friend.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
from friend.controllers import friend_invitation_by_email_send_for_api, friend_invitation_by_email_verify_for_api, \
friend_invitation_by_we_vote_id_send_for_api, friend_invite_response_for_api, friend_list_for_api, \
friend_invitation_by_facebook_send_for_api, friend_invitation_by_facebook_verify_for_api
from friend.models import CURRENT_FRIENDS, DELETE_INVITATION_EMAIL_SENT_BY_ME, DELETE_INVITATION_VOTER_SENT_BY_ME, \
FRIEND_INVITATIONS_PROCESSED, FRIEND_INVITATIONS_SENT_TO_ME, FRIEND_INVITATIONS_SENT_BY_ME, \
SUGGESTED_FRIEND_LIST, \
FRIENDS_IN_COMMON, IGNORED_FRIEND_INVITATIONS, ACCEPT_INVITATION, IGNORE_INVITATION, \
UNFRIEND_CURRENT_FRIEND
import json
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def friend_invitation_by_email_send_view(request): # friendInvitationByEmailSend
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_address_array = request.GET.getlist('email_address_array[]', "")
first_name_array = request.GET.getlist('first_name_array[]', "")
last_name_array = request.GET.getlist('last_name_array[]', "")
email_addresses_raw = request.GET.get('email_addresses_raw', "")
invitation_message = request.GET.get('invitation_message', "")
sender_email_address = request.GET.get('sender_email_address', "")
results = friend_invitation_by_email_send_for_api(voter_device_id, email_address_array, first_name_array,
last_name_array, email_addresses_raw,
invitation_message, sender_email_address)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'sender_voter_email_address_missing': results['sender_voter_email_address_missing'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_invitation_by_email_verify_view(request): # friendInvitationByEmailVerify
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
invitation_secret_key = request.GET.get('invitation_secret_key', "")
results = friend_invitation_by_email_verify_for_api(voter_device_id, invitation_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_has_data_to_preserve': results['voter_has_data_to_preserve'],
'invitation_found': results['invitation_found'],
'attempted_to_approve_own_invitation': results['attempted_to_approve_own_invitation'],
'invitation_secret_key': invitation_secret_key,
'invitation_secret_key_belongs_to_this_voter': results['invitation_secret_key_belongs_to_this_voter'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_invitation_by_facebook_send_view(request): # friendInvitationByFacebookSend
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
recipients_facebook_id_array = request.GET.getlist('recipients_facebook_id_array[]', "")
recipients_facebook_name_array = request.GET.getlist('recipients_facebook_name_array[]', "")
facebook_request_id = request.GET.get('facebook_request_id', "")
results = friend_invitation_by_facebook_send_for_api(voter_device_id, recipients_facebook_id_array,
recipients_facebook_name_array, facebook_request_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'all_friends_facebook_link_created_results': results['all_friends_facebook_link_created_results'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_invitation_by_facebook_verify_view(request): # friendInvitationByFacebookVerify
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
facebook_request_id = request.GET.get('facebook_request_id', "")
recipient_facebook_id = request.GET.get('recipient_facebook_id', "")
sender_facebook_id = request.GET.get('sender_facebook_id', "")
results = friend_invitation_by_facebook_verify_for_api(voter_device_id, facebook_request_id,
recipient_facebook_id, sender_facebook_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_has_data_to_preserve': results['voter_has_data_to_preserve'],
'invitation_found': results['invitation_found'],
'attempted_to_approve_own_invitation': results['attempted_to_approve_own_invitation'],
'facebook_request_id': facebook_request_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_invitation_by_we_vote_id_send_view(request): # friendInvitationByWeVoteIdSend
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
invitation_message = request.GET.get('invitation_message', "")
other_voter_we_vote_id = request.GET.get('other_voter_we_vote_id', "")
results = friend_invitation_by_we_vote_id_send_for_api(voter_device_id, other_voter_we_vote_id, invitation_message)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_invite_response_view(request): # friendInviteResponse
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_invite_response = request.GET.get('kind_of_invite_response', ACCEPT_INVITATION)
if not kind_of_invite_response in(ACCEPT_INVITATION, DELETE_INVITATION_EMAIL_SENT_BY_ME,
DELETE_INVITATION_VOTER_SENT_BY_ME, IGNORE_INVITATION, UNFRIEND_CURRENT_FRIEND):
kind_of_invite_response = ACCEPT_INVITATION
other_voter_we_vote_id = request.GET.get('voter_we_vote_id', "")
recipient_voter_email = request.GET.get('recipient_voter_email', "")
results = friend_invite_response_for_api(voter_device_id=voter_device_id,
kind_of_invite_response=kind_of_invite_response,
other_voter_we_vote_id=other_voter_we_vote_id,
recipient_voter_email=recipient_voter_email)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_we_vote_id': other_voter_we_vote_id,
'kind_of_invite_response': kind_of_invite_response,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def friend_list_view(request): # friendList
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_list = request.GET.get('kind_of_list', CURRENT_FRIENDS)
if kind_of_list in(CURRENT_FRIENDS, FRIEND_INVITATIONS_PROCESSED,
FRIEND_INVITATIONS_SENT_TO_ME, FRIEND_INVITATIONS_SENT_BY_ME, FRIENDS_IN_COMMON,
IGNORED_FRIEND_INVITATIONS, SUGGESTED_FRIEND_LIST):
kind_of_list_we_are_looking_for = kind_of_list
else:
kind_of_list_we_are_looking_for = CURRENT_FRIENDS
state_code = request.GET.get('state_code', "")
results = friend_list_for_api(voter_device_id=voter_device_id,
kind_of_list_we_are_looking_for=kind_of_list_we_are_looking_for,
state_code=state_code)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'state_code': state_code,
'kind_of_list': kind_of_list_we_are_looking_for,
'friend_list_found': results['friend_list_found'],
'friend_list': results['friend_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_friend.py",
"copies": "1",
"size": "9697",
"license": "mit",
"hash": -959730269688284000,
"line_mean": 50.579787234,
"line_max": 119,
"alpha_frac": 0.6143137053,
"autogenerated": false,
"ratio": 3.5197822141560797,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46340959194560793,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_measure.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from measure.controllers import add_measure_name_alternatives_to_measure_list_light, measure_retrieve_for_api, \
retrieve_measure_list_for_all_upcoming_elections
import wevote_functions.admin
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def measure_list_for_upcoming_elections_retrieve_api_view(request): # measureListForUpcomingElectionsRetrieve
"""
Ask for all measures for the elections in google_civic_election_id_list
:param request:
:return:
"""
status = ""
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list[]')
state_code = request.GET.get('state_code', '')
# We will need all candidates for all upcoming elections so we can search the HTML of
# the possible voter guide for these names
measure_list_light = []
results = retrieve_measure_list_for_all_upcoming_elections(google_civic_election_id_list,
limit_to_this_state_code=state_code)
if results['measure_list_found']:
measure_list_light = results['measure_list_light']
expand_results = add_measure_name_alternatives_to_measure_list_light(measure_list_light)
if expand_results['success']:
measure_list_light = expand_results['measure_list_light']
google_civic_election_id_list = results['google_civic_election_id_list']
status += results['status']
success = results['success']
json_data = {
'status': status,
'success': success,
'google_civic_election_id_list': google_civic_election_id_list,
'measure_list': measure_list_light,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def measure_retrieve_view(request): # measureRetrieve
measure_id = request.GET.get('measure_id', 0)
measure_we_vote_id = request.GET.get('measure_we_vote_id', None)
return measure_retrieve_for_api(measure_id, measure_we_vote_id)
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_measure.py",
"copies": "1",
"size": "2317",
"license": "mit",
"hash": -2015509019839633,
"line_mean": 41.1272727273,
"line_max": 112,
"alpha_frac": 0.6685369012,
"autogenerated": false,
"ratio": 3.6146645865834635,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4783201487783464,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_misc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from measure.controllers import measure_retrieve_for_api
from office.controllers import office_retrieve_for_api
from quick_info.controllers import quick_info_retrieve_for_api
from search.controllers import search_all_for_api
import wevote_functions.admin
from wevote_functions.functions import generate_voter_device_id, get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def device_id_generate_view(request): # deviceIdGenerate
"""
This API call is used by clients to generate a transient unique identifier (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.
:param request:
:return: Unique device id that can be stored in a cookie
"""
voter_device_id = generate_voter_device_id() # Stored in cookie elsewhere
logger.debug("apis_v1/views.py, device_id_generate-voter_device_id: {voter_device_id}".format(
voter_device_id=voter_device_id
))
if positive_value_exists(voter_device_id):
success = True
status = "DEVICE_ID_GENERATE_VALUE_DOES_NOT_EXIST"
else:
success = False
status = "DEVICE_ID_GENERATE_VALUE_EXISTS"
json_data = {
'voter_device_id': voter_device_id,
'success': success,
'status': status,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def measure_retrieve_view(request): # measureRetrieve
measure_id = request.GET.get('measure_id', 0)
measure_we_vote_id = request.GET.get('measure_we_vote_id', None)
return measure_retrieve_for_api(measure_id, measure_we_vote_id)
def office_retrieve_view(request): # officeRetrieve
office_id = request.GET.get('office_id', 0)
office_we_vote_id = request.GET.get('office_we_vote_id', None)
return office_retrieve_for_api(office_id, office_we_vote_id)
def quick_info_retrieve_view(request):
"""
Retrieve the information necessary to populate a bubble next to a ballot item.
:param request:
:return:
"""
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', "")
return quick_info_retrieve_for_api(kind_of_ballot_item=kind_of_ballot_item,
ballot_item_we_vote_id=ballot_item_we_vote_id)
def search_all_view(request): # searchAll
"""
Find information anywhere in the We Vote universe.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
text_from_search_field = request.GET.get('text_from_search_field', '')
if not positive_value_exists(text_from_search_field):
status = 'MISSING_TEXT_FROM_SEARCH_FIELD'
json_data = {
'status': status,
'success': False,
'text_from_search_field': text_from_search_field,
'voter_device_id': voter_device_id,
'search_results': [],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = search_all_for_api(text_from_search_field, voter_device_id)
status = "UNABLE_TO_FIND_ANY_SEARCH_RESULTS "
search_results = []
if results['search_results_found']:
search_results = results['search_results']
status = results['status']
else:
status += results['status']
json_data = {
'status': status,
'success': True,
'text_from_search_field': text_from_search_field,
'voter_device_id': voter_device_id,
'search_results': search_results,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_misc.py",
"copies": "1",
"size": "4233",
"license": "mit",
"hash": -5662861473171419000,
"line_mean": 38.1944444444,
"line_max": 109,
"alpha_frac": 0.655090952,
"autogenerated": false,
"ratio": 3.4810855263157894,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9631759362780381,
"avg_score": 0.0008834231070815458,
"num_lines": 108
} |
# apis_v1/views/views_misc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
import json
import sys
from office.controllers import office_retrieve_for_api
from quick_info.controllers import quick_info_retrieve_for_api
from search.controllers import search_all_for_api
import wevote_functions.admin
from voter.models import VoterDeviceLinkManager
from wevote_functions.functions import generate_voter_device_id, get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def device_id_generate_view(request): # deviceIdGenerate
"""
This API call is used by clients to generate a transient unique identifier (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.
:param request:
:return: Unique device id that can be stored in a cookie
"""
voter_device_id = generate_voter_device_id() # Stored in cookie elsewhere
if 'test' not in sys.argv:
logger.debug("apis_v1/views.py, device_id_generate-voter_device_id: {voter_device_id}".format(
voter_device_id=voter_device_id))
if positive_value_exists(voter_device_id):
success = True
status = "DEVICE_ID_GENERATE_VALUE_DOES_NOT_EXIST"
else:
success = False
status = "DEVICE_ID_GENERATE_VALUE_EXISTS"
json_data = {
'voter_device_id': voter_device_id,
'success': success,
'status': status,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def device_store_firebase_fcm_token_view(request): # deviceStoreFirebaseCloudMessagingToken
"""
This API call is used by clients to add a Firebase Cloud Messaging token ~ FCB Token to the device_id record.
FCM Tokens are generated by Google's Firebase Cloud Messaging service, and are unique for every device. FCM Tokens
allow the cloud messaging service to send messages (Notifications) to individual devices.
:param request:
:return: Success/Failure status
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# cloud_messaging.test_msg_to_my_phone()
if positive_value_exists(voter_device_id):
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
firebase_fcm_token = request.GET.get('firebase_fcm_token', "")
platform_type = request.GET.get('platform_type', "")
if positive_value_exists(firebase_fcm_token) and len(firebase_fcm_token) > 90:
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_device_link.firebase_fcm_token = firebase_fcm_token # Sept 2020, was 180 characters long
if positive_value_exists(platform_type):
voter_device_link.platform_type = platform_type
voter_device_link.save()
success = True
status = "FIREBASE_TOKEN_ADDED_TO_VOTER_DEVICE_TOKEN "
else:
success = False
status = "MATCHING_DEVICE_ID_NOT_FOUND_AND_FIREBASE_TOKEN_WAS_NOT_ADDED "
else:
success = False
status = "FIREBASE_TOKEN_IS_INVALID_AND_WAS_NOT_ADDED "
else:
success = False
status = "RECEIVED_VOTER_DEVICE_ID_IS_INVALID_AND_FIREBASE_TOKEN_WAS_NOT_ADDED "
json_data = {
'voter_device_id': voter_device_id,
'success': success,
'status': status,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def office_retrieve_view(request): # officeRetrieve
office_id = request.GET.get('office_id', 0)
office_we_vote_id = request.GET.get('office_we_vote_id', None)
return office_retrieve_for_api(office_id, office_we_vote_id)
def quick_info_retrieve_view(request):
"""
Retrieve the information necessary to populate a bubble next to a ballot item.
:param request:
:return:
"""
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', "")
return quick_info_retrieve_for_api(kind_of_ballot_item=kind_of_ballot_item,
ballot_item_we_vote_id=ballot_item_we_vote_id)
def search_all_view(request): # searchAll
"""
Find information anywhere in the We Vote universe.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
text_from_search_field = request.GET.get('text_from_search_field', '')
search_scope_list = request.GET.getlist('search_scope_list[]')
search_scope_list = list(filter(None, search_scope_list))
# search_scope_list options
# PN = POLITICIAN_NAME
if not positive_value_exists(text_from_search_field):
status = 'MISSING_TEXT_FROM_SEARCH_FIELD'
json_data = {
'status': status,
'success': False,
'text_from_search_field': text_from_search_field,
'voter_device_id': voter_device_id,
'search_results': [],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = search_all_for_api(
text_from_search_field=text_from_search_field,
voter_device_id=voter_device_id,
search_scope_list=search_scope_list)
# results = search_all_elastic_for_api(text_from_search_field, voter_device_id) #
status = "UNABLE_TO_FIND_ANY_SEARCH_RESULTS "
search_results = []
if results['search_results_found']:
search_results = results['search_results']
status = results['status']
else:
status += results['status']
json_data = {
'status': status,
'success': True,
'text_from_search_field': text_from_search_field,
'voter_device_id': voter_device_id,
'search_results': search_results,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_misc.py",
"copies": "1",
"size": "6705",
"license": "mit",
"hash": -6481073472814796000,
"line_mean": 41.9807692308,
"line_max": 119,
"alpha_frac": 0.6521998509,
"autogenerated": false,
"ratio": 3.4940072954663886,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46462071463663884,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_organization.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from follow.models import UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW, UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW, \
UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW_ON_TWITTER, UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS, \
UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS_ON_TWITTER, UPDATE_SUGGESTIONS_ALL, \
FOLLOW_SUGGESTIONS_FROM_FRIENDS_ON_TWITTER, FOLLOW_SUGGESTIONS_FROM_FRIENDS, \
FOLLOW_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW
from apis_v1.controllers import organization_count, organization_follow, organization_follow_ignore, \
organization_stop_following
from config.base import get_environment_variable
from django.http import HttpResponse
from django_user_agents.utils import get_user_agent
from follow.controllers import organization_suggestion_tasks_for_api
import json
from organization.controllers import organization_retrieve_for_api, organization_save_for_api, \
organization_search_for_api, organizations_followed_retrieve_for_api
from organization.models import UNKNOWN
from voter.models import voter_has_authority, VoterManager
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_voter_device_id, \
get_maximum_number_to_retrieve_from_request, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def organization_count_view(request):
return organization_count()
def organization_follow_api_view(request): # organizationFollow
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_id = request.GET.get('organization_id', 0)
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
organization_twitter_handle = request.GET.get('organization_twitter_handle', '')
organization_follow_based_on_issue = request.GET.get('organization_follow_based_on_issue', False)
organization_follow_based_on_issue = positive_value_exists(organization_follow_based_on_issue)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
return organization_follow(voter_device_id=voter_device_id, organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
organization_twitter_handle=organization_twitter_handle,
organization_follow_based_on_issue=organization_follow_based_on_issue,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def organization_stop_following_api_view(request): # organizationStopFollowing
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_id = request.GET.get('organization_id', 0)
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
return organization_stop_following(voter_device_id=voter_device_id, organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def organization_follow_ignore_api_view(request): # organizationFollowIgnore
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_id = request.GET.get('organization_id', 0)
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
return organization_follow_ignore(voter_device_id=voter_device_id, organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def organization_retrieve_view(request):
"""
Retrieve a single organization based on unique identifier
:param request:
:return:
"""
organization_id = request.GET.get('organization_id', 0)
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return organization_retrieve_for_api(
organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
voter_device_id=voter_device_id,
)
def organization_save_view(request): # organizationSave
"""
Save a single organization based on unique identifier
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_email = request.GET.get('organization_email', False)
organization_description = request.GET.get('organization_description', False)
organization_facebook = request.GET.get('organization_facebook', False)
organization_id = request.GET.get('organization_id', 0)
organization_image = request.GET.get('organization_image', False)
organization_instagram_handle = request.GET.get('organization_instagram_handle', False)
organization_name = request.GET.get('organization_name', False)
organization_type = request.GET.get('organization_type', False)
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
organization_website = request.GET.get('organization_website', False)
# We only want to allow save if either this is your organization (i.e., you have the Twitter handle)
organization_linked_to_this_voter = False
voter_owns_twitter_handle = False
voter_owns_facebook_id = False
# Twitter specific
organization_twitter_handle = request.GET.get('organization_twitter_handle', False)
refresh_from_twitter = request.GET.get('refresh_from_twitter', False)
# Facebook specific
facebook_id = request.GET.get('facebook_id', False)
if facebook_id is not False:
facebook_id = convert_to_int(facebook_id)
facebook_email = request.GET.get('facebook_email', False)
facebook_profile_image_url_https = request.GET.get('facebook_profile_image_url_https', False)
# admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer
authority_required = {'admin', 'political_data_manager', 'verified_volunteer'}
voter_has_authority_required = False
if voter_has_authority(request, authority_required):
voter_has_authority_required = True
else:
voter_manager = VoterManager()
voter_results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
if voter_results['voter_found']:
voter = voter_results['voter']
# Is this voter linked to this organization?
if positive_value_exists(voter.linked_organization_we_vote_id) \
and positive_value_exists(organization_we_vote_id) \
and voter.linked_organization_we_vote_id == organization_we_vote_id:
organization_linked_to_this_voter = True
# Does this voter have the same Facebook id as this organization? If so, link this organization to
# this particular voter
voter_facebook_id = voter_manager.fetch_facebook_id_from_voter_we_vote_id(voter.we_vote_id)
if positive_value_exists(voter_facebook_id) \
and positive_value_exists(facebook_id) \
and voter_facebook_id == facebook_id:
voter_owns_facebook_id = True
# Does this voter have the same Twitter handle as this organization? If so, link this organization to
# this particular voter
voter_twitter_handle = voter_manager.fetch_twitter_handle_from_voter_we_vote_id(voter.we_vote_id)
if positive_value_exists(voter_twitter_handle) \
and positive_value_exists(organization_twitter_handle) \
and voter_twitter_handle.lower() == organization_twitter_handle.lower():
voter_owns_twitter_handle = True
if not voter_has_authority_required:
if not voter_owns_twitter_handle and not voter_owns_facebook_id and not organization_linked_to_this_voter:
# Only refuse entry if *both* conditions are not met
results = {
'status': "VOTER_LACKS_AUTHORITY_TO_SAVE_ORGANIZATION",
'success': False,
'facebook_id': facebook_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'new_organization_created': False,
'organization_description': organization_description,
'organization_email': organization_email,
'organization_facebook': organization_facebook,
'organization_id': organization_id,
'organization_instagram_handle': organization_instagram_handle,
'organization_name': organization_name,
'organization_photo_url': organization_image,
'organization_twitter_handle': organization_twitter_handle,
'organization_type': organization_type,
'organization_we_vote_id': organization_we_vote_id,
'organization_website': organization_website,
'refresh_from_twitter': refresh_from_twitter,
'twitter_followers_count': 0,
'twitter_description': "",
}
return HttpResponse(json.dumps(results), content_type='application/json')
results = organization_save_for_api(
voter_device_id=voter_device_id, organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
organization_name=organization_name, organization_description=organization_description,
organization_email=organization_email,
organization_website=organization_website, organization_twitter_handle=organization_twitter_handle,
organization_facebook=organization_facebook, organization_instagram_handle=organization_instagram_handle,
organization_image=organization_image,
organization_type=organization_type, refresh_from_twitter=refresh_from_twitter,
facebook_id=facebook_id, facebook_email=facebook_email,
facebook_profile_image_url_https=facebook_profile_image_url_https,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def organization_search_view(request): # organizationSearch
"""
Search for organizations based on a few search terms
:param request:
:return:
"""
organization_search_term = request.GET.get('organization_search_term', '')
organization_name = request.GET.get('organization_name', '')
organization_twitter_handle = request.GET.get('organization_twitter_handle', '')
organization_website = request.GET.get('organization_website', '')
organization_email = request.GET.get('organization_email', '')
exact_match = positive_value_exists(request.GET.get('exact_match', False))
return organization_search_for_api(organization_search_term=organization_search_term,
organization_name=organization_name,
organization_twitter_handle=organization_twitter_handle,
organization_website=organization_website,
organization_email=organization_email,
exact_match=exact_match)
def organization_suggestion_tasks_view(request):
"""
This will provide list of suggested organizations to follow.
These suggestions are generated from twitter ids i follow, or organization of my friends follow.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_suggestion_task = request.GET.get('kind_of_suggestion_task',
UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW)
kind_of_follow_task = request.GET.get('kind_of_follow_task', '')
if kind_of_suggestion_task not in (UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW,
UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW,
UPDATE_SUGGESTIONS_FROM_WHAT_FRIENDS_FOLLOW_ON_TWITTER,
UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS,
UPDATE_SUGGESTIONS_FROM_WHAT_FRIEND_FOLLOWS_ON_TWITTER,
UPDATE_SUGGESTIONS_ALL):
kind_of_suggestion_task = UPDATE_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW
if kind_of_follow_task not in (FOLLOW_SUGGESTIONS_FROM_TWITTER_IDS_I_FOLLOW, FOLLOW_SUGGESTIONS_FROM_FRIENDS,
FOLLOW_SUGGESTIONS_FROM_FRIENDS_ON_TWITTER):
kind_of_follow_task = ''
results = organization_suggestion_tasks_for_api(voter_device_id=voter_device_id,
kind_of_suggestion_task=kind_of_suggestion_task,
kind_of_follow_task=kind_of_follow_task)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'kind_of_suggestion_task': kind_of_suggestion_task,
'kind_of_follow_task': kind_of_follow_task,
'organization_suggestion_task_saved': results['organization_suggestion_task_saved'],
'organization_suggestion_list': results['organization_suggestion_list'],
'organization_suggestion_followed_list': results['organization_suggestion_followed_list']
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def organizations_followed_retrieve_api_view(request): # organizationsFollowedRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
auto_followed_from_twitter_suggestion = request.GET.get('auto_followed_from_twitter_suggestion', False)
return organizations_followed_retrieve_for_api(voter_device_id=voter_device_id,
maximum_number_to_retrieve=maximum_number_to_retrieve,
auto_followed_from_twitter_suggestion=
auto_followed_from_twitter_suggestion)
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_organization.py",
"copies": "1",
"size": "15026",
"license": "mit",
"hash": 6730277787073531000,
"line_mean": 56.7923076923,
"line_max": 118,
"alpha_frac": 0.671169972,
"autogenerated": false,
"ratio": 3.853808668889459,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5024978640889459,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_organization.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from issue.models import *
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from issue.controllers import retrieve_issues_not_linked_to_organization_for_api, \
retrieve_issues_linked_to_organization_for_api
from issue.models import LINKED_BY_ORGANIZATION, BLOCKED_BY_ORGANIZATION
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def issues_linked_to_organization_view(request): # issuesLinkedToOrganization
organization_we_vote_id = request.GET.get('organization_we_vote_id')
issues_linked_result = retrieve_issues_linked_to_organization_for_api(organization_we_vote_id)
status = issues_linked_result['status']
success = issues_linked_result['success']
issues_linked = []
if issues_linked_result['issue_list_found']:
issues_linked = issues_linked_result['issue_list']
json_data = {
'success': success,
'status': status,
'organization_we_vote_id': organization_we_vote_id,
'issue_list': issues_linked,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def issues_to_link_to_for_organization_view(request): # issuesToLinkToForOrganization
organization_we_vote_id = request.GET.get('organization_we_vote_id')
issues_linked_result = retrieve_issues_not_linked_to_organization_for_api(organization_we_vote_id)
status = issues_linked_result['status']
success = issues_linked_result['success']
issues_to_be_linked_to = []
if issues_linked_result['issue_list_found']:
issues_to_be_linked_to = issues_linked_result['issue_list']
json_data = {
'success': success,
'status': status,
'organization_we_vote_id': organization_we_vote_id,
'issue_list': issues_to_be_linked_to,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def organization_link_to_issue_view(request):
organization_we_vote_id = request.GET.get('organization_we_vote_id', False)
issue_we_vote_id = request.GET.get('issue_we_vote_id', False)
organization_linked_to_issue = positive_value_exists(request.GET.get('organization_linked_to_issue', True))
reason_for_link = request.GET.get('reason_for_link', LINKED_BY_ORGANIZATION)
reason_for_unlink = request.GET.get('reason_for_unlink', BLOCKED_BY_ORGANIZATION)
status = ''
success = True
if not positive_value_exists(organization_we_vote_id):
status += ' ORGANIZATION_WE_VOTE_ID_NOT_PROVIDED'
success = False
if not positive_value_exists(issue_we_vote_id):
status += ' ISSUE_WE_VOTE_ID_NOT_PROVIDED'
success = False
if not success:
json_data = {
'success': False,
'status': status,
'organization_we_vote_id': organization_we_vote_id,
'issue_we_vote_id': issue_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
issue_id = False
link_manager = OrganizationLinkToIssueManager()
if organization_linked_to_issue:
link_result = link_manager.link_organization_to_issue(
organization_we_vote_id, issue_id, issue_we_vote_id, reason_for_link)
else:
link_result = link_manager.unlink_organization_to_issue(
organization_we_vote_id, issue_id, issue_we_vote_id, reason_for_unlink)
link_issue_on_stage = {}
organization_linked_to_issue = False
if link_result['success']:
link_issue_from_result = link_result['link_issue']
link_issue_on_stage = {
'organization_we_vote_id': link_issue_from_result.organization_we_vote_id,
'issue_id': link_issue_from_result.issue_id,
'issue_we_vote_id': link_issue_from_result.issue_we_vote_id,
'link_active': link_issue_from_result.link_active,
'reason_for_link': link_issue_from_result.reason_for_link,
'link_blocked': link_issue_from_result.link_blocked,
'reason_link_is_blocked': link_issue_from_result.reason_link_is_blocked
}
organization_linked_to_issue = link_issue_from_result.link_active
link_result['organization_we_vote_id'] = organization_we_vote_id
link_result['organization_linked_to_issue'] = organization_linked_to_issue
link_result['link_issue'] = link_issue_on_stage
return HttpResponse(json.dumps(link_result), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_issues.py",
"copies": "2",
"size": "4758",
"license": "mit",
"hash": -6043446872625550000,
"line_mean": 42.6513761468,
"line_max": 111,
"alpha_frac": 0.6862126944,
"autogenerated": false,
"ratio": 3.4378612716763004,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51240739660763,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_pledge_to_vote.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from pledge_to_vote.controllers import pledge_to_vote_with_voter_guide_for_api
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def pledge_to_vote_with_voter_guide_view(request): # pledgeToVoteWithVoterGuide
status = ""
success = False
missing_required_variable = False
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_we_vote_id = request.GET.get('voter_guide_we_vote_id', '')
delete_pledge = request.GET.get('ballot_item_we_vote_id', False)
if not positive_value_exists(voter_guide_we_vote_id):
status += "MISSING_VOTER_GUIDE_WE_VOTE_ID "
success = False
missing_required_variable = True
if missing_required_variable:
json_data = {
'status': status,
'success': success,
'delete_pledge': delete_pledge,
'google_civic_election_id': 0,
'organization_we_vote_id': "",
'pledge_statistics_found': False,
'pledge_goal': 0,
'pledge_count': 0,
'voter_has_pledged': False,
'voter_device_id': voter_device_id,
'voter_guide_we_vote_id': voter_guide_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
pledge_results = pledge_to_vote_with_voter_guide_for_api(voter_device_id, voter_guide_we_vote_id, delete_pledge)
status += pledge_results['status']
json_data = {
'status': status,
'success': pledge_results['success'],
'delete_pledge': delete_pledge,
'google_civic_election_id': pledge_results['google_civic_election_id'],
'organization_we_vote_id': pledge_results['organization_we_vote_id'],
'pledge_statistics_found': pledge_results['pledge_statistics_found'],
'pledge_goal': pledge_results['pledge_goal'],
'pledge_count': pledge_results['pledge_count'],
'voter_has_pledged': pledge_results['voter_has_pledged'],
'voter_device_id': voter_device_id,
'voter_guide_we_vote_id': voter_guide_we_vote_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_pledge_to_vote.py",
"copies": "2",
"size": "2766",
"license": "mit",
"hash": 311591141984737540,
"line_mean": 42.9047619048,
"line_max": 116,
"alpha_frac": 0.6160520607,
"autogenerated": false,
"ratio": 3.3405797101449277,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9952297806080583,
"avg_score": 0.0008667929528685755,
"num_lines": 63
} |
# apis_v1/views/views_position.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from ballot.controllers import figure_out_google_civic_election_id_voter_is_watching
from ballot.models import OFFICE, CANDIDATE, MEASURE
from position.controllers import calculate_positions_count_for_all_ballot_items_for_api, \
count_for_all_ballot_items_from_position_network_score_for_api, \
position_list_for_ballot_item_for_api, position_list_for_ballot_item_from_friends_for_api, \
position_list_for_opinion_maker_for_api, \
position_list_for_voter_for_api, \
position_retrieve_for_api, position_save_for_api
from position.models import ANY_STANCE, SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE, PERCENT_RATING, \
FRIENDS_ONLY, PUBLIC_ONLY, FRIENDS_AND_PUBLIC
from support_oppose_deciding.controllers import position_oppose_count_for_ballot_item_for_api, \
position_support_count_for_ballot_item_for_api, \
position_public_oppose_count_for_ballot_item_for_api, \
position_public_support_count_for_ballot_item_for_api, \
positions_count_for_one_ballot_item_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_bool, get_voter_device_id, \
is_speaker_type_organization, is_speaker_type_public_figure, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def position_list_for_ballot_item_view(request): # positionListForBallotItem
"""
:param request:
:return:
"""
stance = request.GET.get('stance', ANY_STANCE)
if stance in (ANY_STANCE, SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE, PERCENT_RATING):
stance_we_are_looking_for = stance
else:
stance_we_are_looking_for = ANY_STANCE
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', "")
private_citizens_only = positive_value_exists(request.GET.get('private_citizens_only', False))
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return position_list_for_ballot_item_for_api(office_id=office_id,
office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id,
measure_we_vote_id=measure_we_vote_id,
stance_we_are_looking_for=stance_we_are_looking_for,
private_citizens_only=private_citizens_only)
def position_list_for_ballot_item_from_friends_view(request): # positionListForBallotItemFromFriends
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
stance = request.GET.get('stance', ANY_STANCE)
if stance in (ANY_STANCE, SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE, PERCENT_RATING):
stance_we_are_looking_for = stance
else:
stance_we_are_looking_for = ANY_STANCE
friends_vs_public_incoming = request.GET.get('friends_vs_public', FRIENDS_AND_PUBLIC)
if friends_vs_public_incoming in (FRIENDS_ONLY, PUBLIC_ONLY, FRIENDS_AND_PUBLIC):
friends_vs_public = friends_vs_public_incoming
else:
friends_vs_public = FRIENDS_AND_PUBLIC
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', "")
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
office_id = 0
office_we_vote_id = ''
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
elif kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
elif kind_of_ballot_item == MEASURE:
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
return position_list_for_ballot_item_from_friends_for_api(
voter_device_id=voter_device_id,
friends_vs_public=friends_vs_public,
office_id=office_id,
office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id,
measure_we_vote_id=measure_we_vote_id,
stance_we_are_looking_for=stance_we_are_looking_for)
def position_list_for_opinion_maker_view(request): # positionListForOpinionMaker
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
stance = request.GET.get('stance', ANY_STANCE)
if stance in (ANY_STANCE, SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE, PERCENT_RATING):
stance_we_are_looking_for = stance
else:
stance_we_are_looking_for = ANY_STANCE
friends_vs_public_incoming = request.GET.get('friends_vs_public', ANY_STANCE)
if friends_vs_public_incoming in (FRIENDS_ONLY, PUBLIC_ONLY, FRIENDS_AND_PUBLIC):
friends_vs_public = friends_vs_public_incoming
else:
friends_vs_public = FRIENDS_AND_PUBLIC
kind_of_opinion_maker = request.GET.get('kind_of_opinion_maker', "")
opinion_maker_id = request.GET.get('opinion_maker_id', 0)
opinion_maker_we_vote_id = request.GET.get('opinion_maker_we_vote_id', "")
google_civic_election_id = request.GET.get('google_civic_election_id', '') # The Position tables use str
state_code = request.GET.get('state_code', "")
filter_for_voter = positive_value_exists(request.GET.get('filter_for_voter', True))
filter_out_voter = positive_value_exists(request.GET.get('filter_out_voter', False))
# Make sure filter_for_voter is reset to False if filter_out_voter is true
filter_for_voter = False if filter_out_voter else filter_for_voter
if is_speaker_type_organization(kind_of_opinion_maker):
organization_id = opinion_maker_id
organization_we_vote_id = opinion_maker_we_vote_id
public_figure_id = 0
public_figure_we_vote_id = ''
elif is_speaker_type_public_figure(kind_of_opinion_maker):
organization_id = 0
organization_we_vote_id = ''
public_figure_id = opinion_maker_id
public_figure_we_vote_id = opinion_maker_we_vote_id
else:
organization_id = 0
organization_we_vote_id = ''
public_figure_id = 0
public_figure_we_vote_id = ''
json_data = position_list_for_opinion_maker_for_api(
voter_device_id=voter_device_id,
organization_id=organization_id,
organization_we_vote_id=organization_we_vote_id,
public_figure_id=public_figure_id,
public_figure_we_vote_id=public_figure_we_vote_id,
friends_vs_public=friends_vs_public,
stance_we_are_looking_for=stance_we_are_looking_for,
filter_for_voter=filter_for_voter,
filter_out_voter=filter_out_voter,
google_civic_election_id=google_civic_election_id,
state_code=state_code)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def position_list_for_voter_view(request): # positionListForVoter
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
stance = request.GET.get('stance', ANY_STANCE)
if stance in (ANY_STANCE, SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE, PERCENT_RATING):
stance_we_are_looking_for = stance
else:
stance_we_are_looking_for = ANY_STANCE
friends_vs_public_incoming = request.GET.get('friends_vs_public', ANY_STANCE)
if friends_vs_public_incoming in (FRIENDS_ONLY, PUBLIC_ONLY, FRIENDS_AND_PUBLIC):
friends_vs_public = friends_vs_public_incoming
else:
friends_vs_public = FRIENDS_AND_PUBLIC
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
state_code = request.GET.get('state_code', "")
show_only_this_election = request.GET.get('show_only_this_election', True)
show_only_this_election = positive_value_exists(show_only_this_election)
show_all_other_elections = request.GET.get('show_all_other_elections', False)
show_all_other_elections = positive_value_exists(show_all_other_elections)
# Make sure show_only_this_election is reset to False if filter_out_voter is true
show_only_this_election = False if show_all_other_elections else show_only_this_election
if show_only_this_election or show_all_other_elections and not positive_value_exists(google_civic_election_id):
results = figure_out_google_civic_election_id_voter_is_watching(voter_device_id)
google_civic_election_id = results['google_civic_election_id']
return position_list_for_voter_for_api(voter_device_id=voter_device_id,
friends_vs_public=friends_vs_public,
stance_we_are_looking_for=stance_we_are_looking_for,
show_only_this_election=show_only_this_election,
show_all_other_elections=show_all_other_elections,
google_civic_election_id=google_civic_election_id,
state_code=state_code)
def position_retrieve_view(request):
"""
Retrieve all of the details about a single position based on unique identifier (positionRetrieve)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_we_vote_id = request.GET.get('position_we_vote_id', '')
return position_retrieve_for_api(
position_we_vote_id=position_we_vote_id,
voter_device_id=voter_device_id
)
def position_save_view(request): # positionSave
"""
Save a single position
:param request:
:return:
"""
# We set values that aren't passed in, to False so we know to treat them as null or unchanged. This allows us to
# only change the values we want to
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_we_vote_id = request.GET.get('position_we_vote_id', False)
organization_we_vote_id = request.GET.get('organization_we_vote_id', False)
public_figure_we_vote_id = request.GET.get('public_figure_we_vote_id', False)
voter_we_vote_id = request.GET.get('voter_we_vote_id', False)
google_civic_election_id = request.GET.get('google_civic_election_id', False)
ballot_item_display_name = request.GET.get('ballot_item_display_name', False)
office_we_vote_id = request.GET.get('office_we_vote_id', False)
candidate_we_vote_id = request.GET.get('candidate_we_vote_id', False)
measure_we_vote_id = request.GET.get('measure_we_vote_id', False)
stance = request.GET.get('stance', False)
set_as_public_position = request.GET.get('set_as_public_position', True)
statement_text = request.GET.get('statement_text', False)
statement_html = request.GET.get('statement_html', False)
more_info_url = request.GET.get('more_info_url', False)
results = position_save_for_api(
voter_device_id=voter_device_id,
position_we_vote_id=position_we_vote_id,
organization_we_vote_id=organization_we_vote_id,
public_figure_we_vote_id=public_figure_we_vote_id,
voter_we_vote_id=voter_we_vote_id,
google_civic_election_id=google_civic_election_id,
ballot_item_display_name=ballot_item_display_name,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
stance=stance,
set_as_public_position=set_as_public_position,
statement_text=statement_text,
statement_html=statement_html,
more_info_url=more_info_url,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def position_oppose_count_for_ballot_item_view(request):
"""
Retrieve the number of orgs and friends that oppose this (positionOpposeCountForBallotItem)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return position_oppose_count_for_ballot_item_for_api(
voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def position_support_count_for_ballot_item_view(request):
"""
Retrieve the number of orgs and friends that support this (positionSupportCountForBallotItem)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return position_support_count_for_ballot_item_for_api(
voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def position_public_oppose_count_for_ballot_item_view(request):
"""
Retrieve the number of orgs and public figures that publicly oppose this (positionPublicOpposeCountForBallotItem)
:param request:
:return:
"""
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return position_public_oppose_count_for_ballot_item_for_api(
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def position_public_support_count_for_ballot_item_view(request):
"""
Retrieve the number of orgs and public figures that publicly support this (positionPublicSupportCountForBallotItem)
:param request:
:return:
"""
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return position_public_support_count_for_ballot_item_for_api(
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def positions_count_for_all_ballot_items_view(request): # positionsCountForAllBallotItems
"""
Retrieve the number of support/oppose positions from the voter's network
:param request:
:return:
"""
status = ""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
force_recount = request.GET.get('force_recount', 0)
if positive_value_exists(force_recount):
# Calculate the positions from source tables
calculate_results = calculate_positions_count_for_all_ballot_items_for_api(
voter_device_id=voter_device_id,
google_civic_election_id=google_civic_election_id)
if not positive_value_exists(google_civic_election_id):
google_civic_election_id = calculate_results['google_civic_election_id']
status += calculate_results['status']
# Pull the positions count from cache tables
results = count_for_all_ballot_items_from_position_network_score_for_api(
voter_device_id=voter_device_id,
google_civic_election_id=google_civic_election_id)
status += results['status']
json_data = {
'status': status,
'success': results['success'],
'google_civic_election_id': results['google_civic_election_id'],
'position_counts_list': results['position_counts_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def positions_count_for_one_ballot_item_view(request): # positionsCountForOneBallotItem
"""
Retrieve the number of support/oppose positions from the voter's network for one ballot item
We return results in the same format as positions_count_for_all_ballot_items_view
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', "")
results = positions_count_for_one_ballot_item_for_api(
voter_device_id=voter_device_id,
ballot_item_we_vote_id=ballot_item_we_vote_id)
json_data = {
'status': results['status'],
'success': results['success'],
'position_counts_list': results['position_counts_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_position.py",
"copies": "1",
"size": "20860",
"license": "mit",
"hash": 7985455592691340000,
"line_mean": 44.6455142232,
"line_max": 119,
"alpha_frac": 0.6555129434,
"autogenerated": false,
"ratio": 3.193508879363135,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4349021822763135,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_share.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from share.controllers import shared_item_retrieve_for_api, shared_item_save_for_api
from config.base import get_environment_variable
from django.http import HttpResponse
from django_user_agents.utils import get_user_agent
import json
import wevote_functions.admin
from wevote_functions.functions import convert_to_bool, get_voter_device_id, \
is_speaker_type_organization, is_speaker_type_public_figure, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def shared_item_retrieve_view(request): # sharedItemRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
destination_full_url = request.GET.get('destination_full_url', '')
shared_item_code = request.GET.get('shared_item_code', '')
shared_item_clicked = positive_value_exists(request.GET.get('shared_item_clicked', False))
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
json_data = shared_item_retrieve_for_api(
voter_device_id=voter_device_id,
destination_full_url=destination_full_url,
shared_item_code=shared_item_code,
shared_item_clicked=shared_item_clicked,
user_agent_string=user_agent_string,
user_agent_object=user_agent_object
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def shared_item_save_view(request): # sharedItemSave
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
destination_full_url = request.GET.get('destination_full_url', '')
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
google_civic_election_id = request.GET.get('google_civic_election_id', None)
is_ballot_share = positive_value_exists(request.GET.get('is_ballot_share', False))
is_candidate_share = positive_value_exists(request.GET.get('is_candidate_share', False))
is_measure_share = positive_value_exists(request.GET.get('is_measure_share', False))
is_office_share = positive_value_exists(request.GET.get('is_office_share', False))
is_organization_share = positive_value_exists(request.GET.get('is_organization_share', False))
is_ready_share = positive_value_exists(request.GET.get('is_ready_share', False))
organization_we_vote_id = request.GET.get('organization_we_vote_id', None)
json_data = shared_item_save_for_api(
voter_device_id=voter_device_id,
destination_full_url=destination_full_url,
ballot_item_we_vote_id=ballot_item_we_vote_id,
google_civic_election_id=google_civic_election_id,
is_ballot_share=is_ballot_share,
is_candidate_share=is_candidate_share,
is_measure_share=is_measure_share,
is_office_share=is_office_share,
is_organization_share=is_organization_share,
is_ready_share=is_ready_share,
organization_we_vote_id=organization_we_vote_id,
)
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_share.py",
"copies": "1",
"size": "3228",
"license": "mit",
"hash": -182025012795226000,
"line_mean": 51.064516129,
"line_max": 103,
"alpha_frac": 0.720260223,
"autogenerated": false,
"ratio": 3.2377131394182546,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9366666540825737,
"avg_score": 0.0182613643185035,
"num_lines": 62
} |
# apis_v1/views/views_task.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
import dateutil.parser
import json
import pytz
import requests as python_requests
import subprocess
from django.http import HttpResponse
from background_task import background
from config.base import get_environment_variable, get_environment_variable_default
from scheduled_tasks.models import BackgroundTaskOutputManager
from scheduled_tasks.task_models import WeTask
from scheduled_tasks.task_models_completed import WeTaskCompleted
import wevote_functions.admin
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def delete_task(request): # taskUpdateOne
tid = request.GET.get('id', '')
WeTask().delete_task(tid)
json_data = {
'status': 'status',
'success': 'success',
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def limit_task_history(): # taskUpdateOne
task_retention_days = get_environment_variable_default("SCHEDULED_TASKS_RETAIN_HISTORY", 90) #
success = False
try:
task_retention_days_int = int(task_retention_days)
nowdt = datetime.now(pytz.timezone("America/Los_Angeles"))
limit_dt = nowdt - timedelta(days=task_retention_days_int)
# print("task_retention_days: " + str(task_retention_days))
BackgroundTaskOutputManager().delete_older_tasks(limit_dt=limit_dt)
WeTaskCompleted().delete_older_tasks(limit_dt=limit_dt)
success = True
except Exception as e:
logger.error("limit_task_history threw: " + str(e))
return success
def save_new_task(request): # taskSaveNew
task_parameters = request.GET.get('task_parameters', '')
verbose_name = request.GET.get('verbose_task_name', '')
priority = request.GET.get('priority', '')
run_at = request.GET.get('run_at', '')
repeat = calculate_repeat(request.GET.get('repeat', ''))
repeat_until = request.GET.get('repeat_until', '')
run_at_dt = dateutil.parser.parse(run_at)
repeat_until_dt = dateutil.parser.parse(repeat_until)
if task_parameters.startswith('https://') or task_parameters.startswith('htts://'):
we_task_http(task_parameters=task_parameters, verbose_name=verbose_name, schedule=run_at_dt,
priority=priority, repeat=repeat, repeat_until=repeat_until_dt)
else:
we_task(task_parameters=task_parameters, verbose_name=verbose_name, schedule=run_at_dt,
priority=priority, repeat=repeat, repeat_until=repeat_until_dt)
json_data = {
'status': 'status',
'success': 'success',
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def calculate_repeat(repeat):
if repeat in {'HOURLY', 'DAILY', 'WEEKLY', 'EVERY_2_WEEKS', 'EVERY_4_WEEKS', 'NEVER'}:
if repeat == 'HOURLY':
return 3600
elif repeat == 'DAILY':
return 3600*24
elif repeat == 'WEEKLY':
return 3600*24*7
elif repeat == 'EVERY_2_WEEKS':
return 3600*24*7*2
elif repeat == 'EVERY_4_WEEKS':
return 3600*24*7*4
return 0
def get_repeat_string(repeat):
if repeat == 3600:
return 'HOURLY'
elif repeat == 3600*24:
return 'DAILY'
elif repeat == 3600*24*7:
return 'WEEKLY'
elif repeat == 3600*24*7*2:
return 'EVERY_2_WEEKS'
elif repeat == 3600*24*7*4:
return 'EVERY_4_WEEKS'
else:
return 'NONE'
def insert_output_record(task_parameters, nowdt, output_text):
tlist = WeTaskCompleted().raw_list(limit=1)
# print("WeTaskCompleted.raw_list: " + str(tlist[0].id))
BackgroundTaskOutputManager.create_output_entry(tlist[0].id, date_output_completed=nowdt, output_text=output_text)
success = False
return success
def read_output_record(request):
tid = request.GET.get('id', '')
tlist = BackgroundTaskOutputManager.retrieve_background_task_output_with_completed_id(tid)
text = ""
try:
text = tlist[0].output_text
except Exception as e:
logger.error("read_output_record threw: " + str(e))
json_data = {
'data': text,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
@background()
def we_task(task_parameters, verbose_name="", schedule='', name=''): # pep8 parsing is wrong, these are required
# print("We_task parms: " + task_parameters)
bits = task_parameters.split(" ")
p1 = subprocess.Popen(bits, stdout=subprocess.PIPE)
output = p1.communicate()[0]
nowdt = datetime.now(pytz.timezone("America/Los_Angeles"))
output_string = nowdt.isoformat() + "--" + task_parameters + "--" + output.decode("utf-8")
output_string = output_string.replace('\n', '<br/>')
# print(output_string)
insert_output_record(task_parameters, nowdt, output_string)
limit_task_history()
@background()
def we_task_http(task_parameters, verbose_name="", schedule='', name=''): # pep8 parsing is wrong, these are required
# print("We_task HTTP parms: " + task_parameters)
r = python_requests.get(task_parameters)
output = r.text
# print("r.text ", r.text)
nowdt = datetime.now(pytz.timezone("America/Los_Angeles"))
output_string = nowdt.isoformat() + "--" + task_parameters + "--<br/>" + output
output_string = output_string.replace('\n', '<br/>')
# print(output_string)
insert_output_record(task_parameters, nowdt, output_string)
limit_task_history()
def run_task_immediately(request): # taskRunImmediately
json_data = {
'status': 'status',
'success': 'success',
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_task.py",
"copies": "1",
"size": "6003",
"license": "mit",
"hash": -4059705618453515300,
"line_mean": 33.5,
"line_max": 118,
"alpha_frac": 0.6430118274,
"autogenerated": false,
"ratio": 3.55207100591716,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.469508283331716,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_twitter.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from import_export_twitter.controllers import twitter_identity_retrieve_for_api, twitter_sign_in_start_for_api, \
twitter_sign_in_request_access_token_for_api, twitter_sign_in_request_voter_info_for_api, \
twitter_sign_in_retrieve_for_api, twitter_retrieve_ids_i_follow_for_api, twitter_native_sign_in_save_for_api
import json
from urllib.parse import quote
from urllib.parse import urlencode
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def twitter_identity_retrieve_view(request): # twitterIdentityRetrieve
"""
Find the kind of owner and unique id of this twitter handle. We use this to take an incoming URI like
https://wevote.guide/RepBarbaraLee and return the owner of 'RepBarbaraLee'. (twitterIdentityRetrieve)
:param request:
:return:
"""
twitter_handle = request.GET.get('twitter_handle', '')
if not positive_value_exists(twitter_handle):
status = 'VALID_TWITTER_HANDLE_MISSING'
json_data = {
'status': status,
'success': False,
'twitter_handle': twitter_handle,
'owner_found': False,
'kind_of_owner': '',
'owner_we_vote_id': '',
'owner_id': 0,
'google_civic_election_id': 0,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = twitter_identity_retrieve_for_api(twitter_handle, voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'twitter_handle': results['twitter_handle'],
'owner_found': results['owner_found'],
'kind_of_owner': results['kind_of_owner'],
'owner_we_vote_id': results['owner_we_vote_id'],
'owner_id': results['owner_id'],
'google_civic_election_id': results['google_civic_election_id'],
# These values only returned if kind_of_owner == TWITTER_HANDLE_NOT_FOUND_IN_WE_VOTE
'twitter_description': results['twitter_description'],
'twitter_followers_count': results['twitter_followers_count'],
'twitter_photo_url': results['twitter_photo_url'],
'we_vote_hosted_profile_image_url_large': results['we_vote_hosted_profile_image_url_large'],
'we_vote_hosted_profile_image_url_medium': results['we_vote_hosted_profile_image_url_medium'],
'we_vote_hosted_profile_image_url_tiny': results['we_vote_hosted_profile_image_url_tiny'],
'twitter_profile_banner_url_https': results['twitter_profile_banner_url_https'],
'twitter_user_website': results['twitter_user_website'],
'twitter_name': results['twitter_name'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_sign_in_start_view(request): # twitterSignInStart (Step 1)
"""
Step 1 of the Twitter Sign In Process for the WebApp
Start off the process of signing in with Twitter (twitterSignInStart)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return_url = request.GET.get('return_url', '')
cordova = request.GET.get('cordova', False)
results = twitter_sign_in_start_for_api(voter_device_id, return_url, cordova)
if positive_value_exists(results['jump_to_request_voter_info']) and positive_value_exists(results['return_url']):
next_step_url = WE_VOTE_SERVER_ROOT_URL + "/apis/v1/twitterSignInRequest/" # twitterSignInRequestVoterInfo
next_step_url += "?voter_info_mode=1"
next_step_url += "&voter_device_id=" + voter_device_id
next_step_url += "&return_url=" + quote(results['return_url'], safe='')
next_step_url += "&cordova=" + str(cordova)
return HttpResponseRedirect(next_step_url)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'twitter_redirect_url': results['twitter_redirect_url'],
'voter_info_retrieved': results['voter_info_retrieved'],
'switch_accounts': results['switch_accounts'], # If true, new voter_device_id returned
'cordova': cordova,
}
if cordova:
return twitter_cordova_signin_response(request, json_data)
else:
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_sign_in_request_view(request): # twitterSignInRequest (Switch for Step 1 & Step 2)
voter_info_mode = request.GET.get('voter_info_mode', 0)
if positive_value_exists(voter_info_mode):
return twitter_sign_in_request_voter_info_view(request)
else:
return twitter_sign_in_request_access_token_view(request)
def twitter_sign_in_request_access_token_view(request): # twitterSignInRequestAccessToken (Step 2)
"""
Step 2 of the Twitter Sign In Process (twitterSignInRequestAccessToken) for the WebApp
:param request:
:return:
"""
voter_info_mode = request.GET.get('voter_info_mode', 0)
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
incoming_request_token = request.GET.get('oauth_token', '')
incoming_oauth_verifier = request.GET.get('oauth_verifier', '')
return_url = request.GET.get('return_url', '')
cordova = request.GET.get('cordova', False)
results = twitter_sign_in_request_access_token_for_api(voter_device_id,
incoming_request_token, incoming_oauth_verifier,
return_url, cordova)
if positive_value_exists(results['return_url']):
next_step_url = WE_VOTE_SERVER_ROOT_URL + "/apis/v1/twitterSignInRequest/" # twitterSignInRequestVoterInfo
next_step_url += "?voter_info_mode=1"
next_step_url += "&voter_device_id=" + voter_device_id
next_step_url += "&return_url=" + quote(results['return_url'], safe='')
next_step_url += "&cordova=" + str(cordova)
return HttpResponseRedirect(next_step_url)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'access_token_and_secret_returned': results['access_token_and_secret_returned'],
'cordova': cordova,
'voter_info_mode': voter_info_mode,
}
if cordova:
return twitter_cordova_signin_response(request, json_data)
else:
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_native_sign_in_save_view(request): # twitterNativeSignInSave
"""
For the native "app" react-native-oauth, replaces Steps 1 & 2 of the WebApp Twitter Sign In Process.
Receives twitter_access_token and twitter_access_token_secret from the native app's authenticate() call
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
twitter_access_token = request.GET.get('twitter_access_token', '')
twitter_access_token_secret = request.GET.get('twitter_access_token_secret', '')
results_native = twitter_native_sign_in_save_for_api(voter_device_id, twitter_access_token,
twitter_access_token_secret)
if not results_native['success'] == True:
logger.error("Bad save in twitter_native_sign_in_save_view: " + results_native['status'])
# Call equivalent of oAuth for WebApp Step 3
results_voter_info = twitter_sign_in_request_voter_info_for_api(voter_device_id, "Native API Call, No Return URL")
json_data = {
'status': results_voter_info['status'] + ' ' + results_native['status'],
'success': results_voter_info['success'],
'twitter_handle': results_voter_info['twitter_handle'],
'twitter_handle_found': results_voter_info['twitter_handle_found'],
'twitter_secret_key': results_voter_info['twitter_secret_key'],
'voter_device_id': results_voter_info['voter_device_id'],
'voter_info_retrieved': results_voter_info['voter_info_retrieved'],
'switch_accounts': results_voter_info['switch_accounts'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_sign_in_request_voter_info_view(request): # twitterSignInRequestVoterInfo (Step 3)
"""
Step 3 of the Twitter Sign In Process (twitterSignInRequestVoterInfo)
:param request:
:return:
"""
cordova = request.GET.get('cordova', False)
return_url = request.GET.get('return_url', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_info_mode = request.GET.get('voter_info_mode', 0)
results = twitter_sign_in_request_voter_info_for_api(voter_device_id, return_url)
if positive_value_exists(results['return_url']) and not positive_value_exists(cordova):
return HttpResponseRedirect(results['return_url'])
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': results['voter_device_id'],
'twitter_handle': results['twitter_handle'],
'twitter_handle_found': results['twitter_handle_found'],
'voter_info_mode': voter_info_mode,
'voter_info_retrieved': results['voter_info_retrieved'],
'switch_accounts': results['switch_accounts'],
}
if cordova:
return twitter_cordova_signin_response(request, json_data)
else:
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_cordova_signin_response(request, json_data):
"""
https://medium.com/@jlchereau/stop-using-inappbrowser-for-your-cordova-phonegap-oauth-flow-a806b61a2dc5
:param request:
:return: A webpage that initiates a native scheme for iOS (received in Application.js in the WebApp)
"""
logger.debug("twitter_cordova_signin_response: " + urlencode(json_data))
template_values = {
'query_string': urlencode(json_data),
}
# return render(request, 'cordova/cordova_ios_redirect_to_scheme.html', template_values,
# content_type='text/html')
return render(request, 'cordova/cordova_ios_redirect_to_scheme.html', template_values,
content_type='text/html')
def twitter_sign_in_retrieve_view(request): # twitterSignInRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = twitter_sign_in_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'existing_twitter_account_found': results['existing_twitter_account_found'],
'twitter_profile_image_url_https': results['twitter_profile_image_url_https'],
'twitter_retrieve_attempted': True,
'twitter_secret_key': results['twitter_secret_key'],
'twitter_sign_in_failed': results['twitter_sign_in_failed'],
'twitter_sign_in_found': results['twitter_sign_in_found'],
'twitter_sign_in_verified': results['twitter_sign_in_verified'],
'voter_device_id': voter_device_id,
'voter_has_data_to_preserve': results['voter_has_data_to_preserve'],
'voter_we_vote_id': results['voter_we_vote_id'],
'voter_we_vote_id_attached_to_twitter': results['voter_we_vote_id_attached_to_twitter'],
'we_vote_hosted_profile_image_url_large': results['we_vote_hosted_profile_image_url_large'],
'we_vote_hosted_profile_image_url_medium': results['we_vote_hosted_profile_image_url_medium'],
'we_vote_hosted_profile_image_url_tiny': results['we_vote_hosted_profile_image_url_tiny'],
# 'twitter_who_i_follow': results['twitter_who_i_follow'],
# There are more values we currently aren't returning
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def twitter_retrieve_ids_i_follow_view(request): # twitterRetrieveIdsIFollow
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = twitter_retrieve_ids_i_follow_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'twitter_ids_i_follow': results['twitter_ids_i_follow'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_twitter.py",
"copies": "1",
"size": "14214",
"license": "mit",
"hash": 8815026310988910000,
"line_mean": 48.5261324042,
"line_max": 118,
"alpha_frac": 0.6167862671,
"autogenerated": false,
"ratio": 3.659629248197734,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47764155152977344,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter_guide.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from ballot.controllers import choose_election_from_existing_data
from config.base import get_environment_variable
from django.http import HttpResponse
import json
from voter.models import VoterAddress, VoterAddressManager, VoterDeviceLinkManager
from voter_guide.controllers import voter_guide_possibility_retrieve_for_api, voter_guide_possibility_save_for_api, \
voter_guide_save_for_api, \
voter_guides_followed_retrieve_for_api, voter_guides_ignored_retrieve_for_api, voter_guides_retrieve_for_api, \
voter_guides_followed_by_organization_retrieve_for_api, \
voter_guide_followers_retrieve_for_api, \
voter_guides_to_follow_retrieve_for_api, voter_guides_upcoming_retrieve_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_maximum_number_to_retrieve_from_request, \
get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def voter_guide_possibility_retrieve_view(request): # voterGuidePossibilityRetrieve
"""
Retrieve a previously saved website that may contain a voter guide (voterGuidePossibilityRetrieve)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_possibility_url = request.GET.get('voter_guide_possibility_url', '')
return voter_guide_possibility_retrieve_for_api(voter_device_id=voter_device_id,
voter_guide_possibility_url=voter_guide_possibility_url)
def voter_guide_possibility_save_view(request): # voterGuidePossibilitySave
"""
Save a website that may contain a voter guide (voterGuidePossibilitySave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_possibility_url = request.GET.get('voter_guide_possibility_url', '')
return voter_guide_possibility_save_for_api(voter_device_id=voter_device_id,
voter_guide_possibility_url=voter_guide_possibility_url)
def voter_guides_followed_retrieve_view(request): # voterGuidesFollowedRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_followed_retrieve_for_api(voter_device_id=voter_device_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_followed_by_organization_retrieve_view(request): # voterGuidesFollowedByOrganizationRetrieve
voter_linked_organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
filter_by_this_google_civic_election_id = request.GET.get('filter_by_this_google_civic_election_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_followed_by_organization_retrieve_for_api(
voter_device_id,
voter_linked_organization_we_vote_id=voter_linked_organization_we_vote_id,
filter_by_this_google_civic_election_id=filter_by_this_google_civic_election_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guide_followers_retrieve_view(request): # voterGuideFollowersRetrieve
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guide_followers_retrieve_for_api(
voter_device_id, organization_we_vote_id=organization_we_vote_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guide_save_view(request): # voterGuideSave
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_we_vote_id = request.GET.get('voter_guide_we_vote_id', '')
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
return voter_guide_save_for_api(voter_device_id=voter_device_id,
voter_guide_we_vote_id=voter_guide_we_vote_id,
google_civic_election_id=google_civic_election_id)
def voter_guides_ignored_retrieve_view(request): # voterGuidesIgnoredRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_ignored_retrieve_for_api(voter_device_id=voter_device_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_retrieve_view(request): # voterGuidesRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_we_vote_id = request.GET.get('voter_we_vote_id', '')
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_retrieve_for_api(voter_device_id=voter_device_id,
organization_we_vote_id=organization_we_vote_id,
voter_we_vote_id=voter_we_vote_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_to_follow_retrieve_view(request): # voterGuidesToFollowRetrieve
"""
Retrieve a list of voter_guides that a voter might want to follow (voterGuidesToFollow)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', '')
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', '')
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
search_string = request.GET.get('search_string', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
start_retrieve_at_this_number = request.GET.get('start_retrieve_at_this_number', 0)
filter_voter_guides_by_issue = positive_value_exists(request.GET.get('filter_voter_guides_by_issue', False))
# If we want to show voter guides associated with election first, but then show more after those are exhausted,
# set add_voter_guides_not_from_election to True
add_voter_guides_not_from_election = request.GET.get('add_voter_guides_not_from_election', False)
add_voter_guides_not_from_election = positive_value_exists(add_voter_guides_not_from_election)
if positive_value_exists(ballot_item_we_vote_id):
# We don't need both ballot_item and google_civic_election_id
google_civic_election_id = 0
else:
if positive_value_exists(use_test_election):
google_civic_election_id = 2000 # The Google Civic API Test election
elif positive_value_exists(google_civic_election_id) or google_civic_election_id == 0: # Why "0" election?
# If an election was specified, we can skip down to retrieving the voter_guides
pass
else:
# If here we don't have either a ballot_item or a google_civic_election_id.
# Look in the places we cache google_civic_election_id
google_civic_election_id = 0
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
voter_device_link = voter_device_link_results['voter_device_link']
if voter_device_link_results['voter_device_link_found']:
voter_id = voter_device_link.voter_id
voter_address_manager = VoterAddressManager()
voter_address_results = voter_address_manager.retrieve_address(0, voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
else:
voter_address = VoterAddress()
results = choose_election_from_existing_data(voter_device_link, google_civic_election_id, voter_address)
google_civic_election_id = results['google_civic_election_id']
# In order to return voter_guides that are independent of an election or ballot_item, we need to pass in
# google_civic_election_id as 0
results = voter_guides_to_follow_retrieve_for_api(voter_device_id, kind_of_ballot_item, ballot_item_we_vote_id,
google_civic_election_id, search_string,
start_retrieve_at_this_number, maximum_number_to_retrieve,
filter_voter_guides_by_issue,
add_voter_guides_not_from_election)
return HttpResponse(json.dumps(results['json_data']), content_type='application/json')
def voter_guides_upcoming_retrieve_view(request): # voterGuidesUpcomingRetrieve
"""
Retrieve a list of voter_guides that a voter might want to follow (voterGuidesUpcoming)
:param request:
:return:
"""
status = ""
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list')
if positive_value_exists(google_civic_election_id_list):
if not positive_value_exists(len(google_civic_election_id_list)):
google_civic_election_id_list = []
else:
google_civic_election_id_list = []
results = voter_guides_upcoming_retrieve_for_api(google_civic_election_id_list=google_civic_election_id_list)
status += results['status']
return HttpResponse(json.dumps(results['json_data']), content_type='application/json')
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_voter_guide.py",
"copies": "1",
"size": "10569",
"license": "mit",
"hash": 2425666245986255000,
"line_mean": 57.0714285714,
"line_max": 117,
"alpha_frac": 0.6836976062,
"autogenerated": false,
"ratio": 3.3755988502076013,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4559296456407601,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter_guide.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from ballot.controllers import choose_election_from_existing_data
from django.http import HttpResponse
import json
from api_internal_cache.models import ApiInternalCacheManager
from position.models import FRIENDS_AND_PUBLIC, FRIENDS_ONLY, PUBLIC_ONLY
from voter.models import VoterAddress, VoterAddressManager, VoterDeviceLinkManager, VoterManager
from voter_guide.controllers import voter_guide_possibility_highlights_retrieve_for_api, \
voter_guide_possibility_retrieve_for_api, \
voter_guide_possibility_position_save_for_api, \
voter_guide_possibility_positions_retrieve_for_api, voter_guide_possibility_save_for_api, \
voter_guide_save_for_api, \
voter_guides_followed_retrieve_for_api, voter_guides_ignored_retrieve_for_api, voter_guides_retrieve_for_api, \
voter_guides_followed_by_organization_retrieve_for_api, \
voter_guide_followers_retrieve_for_api, \
voter_guides_to_follow_retrieve_for_api, voter_guides_upcoming_retrieve_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_maximum_number_to_retrieve_from_request, \
get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
def voter_guide_possibility_retrieve_view(request): # voterGuidePossibilityRetrieve
"""
Retrieve a previously saved website that may contain a voter guide (voterGuidePossibilityRetrieve)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
url_to_scan = request.GET.get('url_to_scan', '')
voter_guide_possibility_id = request.GET.get('voter_guide_possibility_id', 0)
return voter_guide_possibility_retrieve_for_api(voter_device_id=voter_device_id,
voter_guide_possibility_id=voter_guide_possibility_id,
url_to_scan=url_to_scan)
def voter_guide_possibility_position_save_view(request): # voterGuidePossibilityPositionSave
"""
Update one possible position from one organization on one page.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_possibility_id = request.GET.get('voter_guide_possibility_id', 0)
voter_guide_possibility_position_id = request.GET.get('voter_guide_possibility_position_id', 0)
ballot_item_name = request.GET.get('ballot_item_name', None)
candidate_twitter_handle = request.GET.get('candidate_twitter_handle', None)
candidate_we_vote_id = request.GET.get('candidate_we_vote_id', None)
measure_we_vote_id = request.GET.get('measure_we_vote_id', None)
more_info_url = request.GET.get('more_info_url', None)
organization_name = request.GET.get('organization_name', None)
organization_twitter_handle = request.GET.get('organization_twitter_handle', None)
organization_we_vote_id = request.GET.get('organization_we_vote_id', None)
position_should_be_removed = request.GET.get('position_should_be_removed', None)
position_stance = request.GET.get('position_stance', None)
possibility_should_be_deleted = request.GET.get('possibility_should_be_deleted', None)
possibility_should_be_ignored = request.GET.get('possibility_should_be_ignored', None)
statement_text = request.GET.get('statement_text', None)
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list[]')
try:
if positive_value_exists(google_civic_election_id_list):
if not positive_value_exists(len(google_civic_election_id_list)):
google_civic_election_id_list = None
else:
google_civic_election_id_list = None
except:
google_civic_election_id_list = None
json_data = voter_guide_possibility_position_save_for_api(
voter_device_id=voter_device_id,
voter_guide_possibility_id=voter_guide_possibility_id,
voter_guide_possibility_position_id=voter_guide_possibility_position_id,
ballot_item_name=ballot_item_name,
position_stance=position_stance,
statement_text=statement_text,
more_info_url=more_info_url,
possibility_should_be_deleted=possibility_should_be_deleted,
possibility_should_be_ignored=possibility_should_be_ignored,
candidate_twitter_handle=candidate_twitter_handle,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
organization_name=organization_name,
organization_twitter_handle=organization_twitter_handle,
organization_we_vote_id=organization_we_vote_id,
position_should_be_removed=position_should_be_removed,
google_civic_election_id_list=google_civic_election_id_list)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_guide_possibility_highlights_retrieve_view(request): # voterGuidePossibilityHighlightsRetrieve
"""
Retrieve the possible highlights from one organization on one page.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
limit_to_existing = request.GET.get('limit_to_existing', '')
url_to_scan = request.GET.get('url_to_scan', '')
pdf_url = request.GET.get('pdf_url', '')
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
json_data = voter_guide_possibility_highlights_retrieve_for_api(
voter_device_id=voter_device_id,
url_to_scan=url_to_scan,
limit_to_existing=limit_to_existing,
pdf_url=pdf_url,
google_civic_election_id=google_civic_election_id)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_guide_possibility_positions_retrieve_view(request): # voterGuidePossibilityPositionsRetrieve
"""
Retrieve the possible positions from one organization on one page.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_possibility_id = request.GET.get('voter_guide_possibility_id', 0)
# print("voter_guide_possibility_id: " + voter_guide_possibility_id)
voter_guide_possibility_position_id = request.GET.get('voter_guide_possibility_position_id', 0)
json_data = voter_guide_possibility_positions_retrieve_for_api(
voter_device_id=voter_device_id,
voter_guide_possibility_id=voter_guide_possibility_id,
voter_guide_possibility_position_id=voter_guide_possibility_position_id)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_guide_possibility_save_view(request): # voterGuidePossibilitySave
"""
Save a website that may contain a voter guide (voterGuidePossibilitySave)
Note that this does not save positions -- we do that with voterGuidePossibilityPositionSave
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_possibility_id = request.GET.get('voter_guide_possibility_id', 0)
voter_guide_possibility_id = convert_to_int(voter_guide_possibility_id)
candidate_we_vote_id = request.GET.get('candidate_we_vote_id', None)
clear_organization_options = request.GET.get('clear_organization_options', None)
contributor_comments = request.GET.get('contributor_comments', None)
contributor_email = request.GET.get('contributor_email', None)
candidates_missing_from_we_vote = request.GET.get('candidates_missing_from_we_vote', None)
capture_detailed_comments = request.GET.get('capture_detailed_comments', None)
hide_from_active_review = request.GET.get('hide_from_active_review', None)
ignore_this_source = request.GET.get('ignore_this_source', None)
internal_notes = request.GET.get('internal_notes', None)
limit_to_this_state_code = request.GET.get('limit_to_this_state_code', None)
organization_we_vote_id = request.GET.get('organization_we_vote_id', None)
possible_candidate_name = request.GET.get('possible_candidate_name', None)
possible_candidate_twitter_handle = request.GET.get('possible_candidate_twitter_handle', None)
possible_organization_name = request.GET.get('possible_organization_name', None)
possible_organization_twitter_handle = request.GET.get('possible_organization_twitter_handle', None)
voter_guide_possibility_type = request.GET.get('voter_guide_possibility_type', None)
return voter_guide_possibility_save_for_api(
voter_device_id=voter_device_id,
voter_guide_possibility_id=voter_guide_possibility_id,
candidates_missing_from_we_vote=candidates_missing_from_we_vote,
capture_detailed_comments=capture_detailed_comments,
clear_organization_options=clear_organization_options,
contributor_comments=contributor_comments,
contributor_email=contributor_email,
hide_from_active_review=hide_from_active_review,
ignore_this_source=ignore_this_source,
internal_notes=internal_notes,
voter_guide_possibility_type=voter_guide_possibility_type,
organization_we_vote_id=organization_we_vote_id,
possible_organization_name=possible_organization_name,
possible_organization_twitter_handle=possible_organization_twitter_handle,
candidate_we_vote_id=candidate_we_vote_id,
possible_candidate_name=possible_candidate_name,
possible_candidate_twitter_handle=possible_candidate_twitter_handle,
limit_to_this_state_code=limit_to_this_state_code)
def voter_guides_followed_retrieve_view(request): # voterGuidesFollowedRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_followed_retrieve_for_api(voter_device_id=voter_device_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_followed_by_organization_retrieve_view(request): # voterGuidesFollowedByOrganizationRetrieve
voter_linked_organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
filter_by_this_google_civic_election_id = request.GET.get('filter_by_this_google_civic_election_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_followed_by_organization_retrieve_for_api(
voter_device_id,
voter_linked_organization_we_vote_id=voter_linked_organization_we_vote_id,
filter_by_this_google_civic_election_id=filter_by_this_google_civic_election_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guide_followers_retrieve_view(request): # voterGuideFollowersRetrieve
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guide_followers_retrieve_for_api(
voter_device_id, organization_we_vote_id=organization_we_vote_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guide_save_view(request): # voterGuideSave
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_guide_we_vote_id = request.GET.get('voter_guide_we_vote_id', '')
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
return voter_guide_save_for_api(voter_device_id=voter_device_id,
voter_guide_we_vote_id=voter_guide_we_vote_id,
google_civic_election_id=google_civic_election_id)
def voter_guides_ignored_retrieve_view(request): # voterGuidesIgnoredRetrieve
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_ignored_retrieve_for_api(voter_device_id=voter_device_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_retrieve_view(request): # voterGuidesRetrieve
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_we_vote_id = request.GET.get('voter_we_vote_id', '')
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
return voter_guides_retrieve_for_api(organization_we_vote_id=organization_we_vote_id,
voter_we_vote_id=voter_we_vote_id,
maximum_number_to_retrieve=maximum_number_to_retrieve)
def voter_guides_to_follow_retrieve_view(request): # voterGuidesToFollowRetrieve
"""
Retrieve a list of voter_guides that a voter might want to follow (voterGuidesToFollow)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', '')
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', '')
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
search_string = request.GET.get('search_string', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
maximum_number_to_retrieve = get_maximum_number_to_retrieve_from_request(request)
start_retrieve_at_this_number = request.GET.get('start_retrieve_at_this_number', 0)
filter_voter_guides_by_issue = positive_value_exists(request.GET.get('filter_voter_guides_by_issue', False))
# If we want to show voter guides associated with election first, but then show more after those are exhausted,
# set add_voter_guides_not_from_election to True
add_voter_guides_not_from_election = request.GET.get('add_voter_guides_not_from_election', False)
add_voter_guides_not_from_election = positive_value_exists(add_voter_guides_not_from_election)
if positive_value_exists(ballot_item_we_vote_id):
# We don't need both ballot_item and google_civic_election_id
google_civic_election_id = 0
else:
if positive_value_exists(use_test_election):
google_civic_election_id = 2000 # The Google Civic API Test election
elif positive_value_exists(google_civic_election_id) or google_civic_election_id == 0: # Why "0" election?
# If an election was specified, we can skip down to retrieving the voter_guides
pass
else:
# If here we don't have either a ballot_item or a google_civic_election_id.
# Look in the places we cache google_civic_election_id
google_civic_election_id = 0
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
voter_device_link = voter_device_link_results['voter_device_link']
if voter_device_link_results['voter_device_link_found']:
voter_id = voter_device_link.voter_id
voter_address_manager = VoterAddressManager()
voter_address_results = voter_address_manager.retrieve_address(0, voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
else:
voter_address = VoterAddress()
results = choose_election_from_existing_data(voter_device_link, google_civic_election_id, voter_address)
google_civic_election_id = results['google_civic_election_id']
# In order to return voter_guides that are independent of an election or ballot_item, we need to pass in
# google_civic_election_id as 0
results = voter_guides_to_follow_retrieve_for_api(voter_device_id, kind_of_ballot_item, ballot_item_we_vote_id,
google_civic_election_id, search_string,
start_retrieve_at_this_number, maximum_number_to_retrieve,
filter_voter_guides_by_issue,
add_voter_guides_not_from_election)
return HttpResponse(json.dumps(results['json_data']), content_type='application/json')
def voter_guides_from_friends_upcoming_retrieve_view(request): # voterGuidesFromFriendsUpcomingRetrieve
"""
Retrieve a list of voter_guides from voter's friends
:param request:
:return:
"""
status = ""
voter_we_vote_id = ''
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list[]')
if positive_value_exists(google_civic_election_id_list):
if not positive_value_exists(len(google_civic_election_id_list)):
google_civic_election_id_list = []
else:
google_civic_election_id_list = []
voter_device_id = get_voter_device_id(request)
voter_manager = VoterManager()
voter_results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
if positive_value_exists(voter_results['voter_found']):
voter_we_vote_id = voter_results['voter'].we_vote_id
else:
status += "VOTER_GUIDES_FROM_FRIENDS-MISSING_VOTER_WE_VOTE_ID "
results = {
'status': status,
'success': False,
'voter_guides': [],
'number_retrieved': 0,
}
return HttpResponse(json.dumps(results), content_type='application/json')
results = voter_guides_upcoming_retrieve_for_api(
google_civic_election_id_list=google_civic_election_id_list, friends_vs_public=FRIENDS_AND_PUBLIC,
voter_we_vote_id=voter_we_vote_id)
status += results['status']
return HttpResponse(json.dumps(results['json_data']), content_type='application/json')
def voter_guides_upcoming_retrieve_view(request): # voterGuidesUpcomingRetrieve
"""
Retrieve a list of voter_guides that a voter might want to follow (voterGuidesUpcoming)
:param request:
:return:
"""
status = ""
api_internal_cache = None
api_internal_cache_found = False
json_data = {}
google_civic_election_id_list = request.GET.getlist('google_civic_election_id_list[]')
if positive_value_exists(google_civic_election_id_list):
if not positive_value_exists(len(google_civic_election_id_list)):
google_civic_election_id_list = []
else:
google_civic_election_id_list = []
# Since this API assembles a lot of data, we pre-cache it. Get the data cached most recently.
api_internal_cache_manager = ApiInternalCacheManager()
election_id_list_serialized = json.dumps(google_civic_election_id_list)
results = api_internal_cache_manager.retrieve_latest_api_internal_cache(
api_name='voterGuidesUpcoming',
election_id_list_serialized=election_id_list_serialized)
if results['api_internal_cache_found']:
api_internal_cache_found = True
api_internal_cache = results['api_internal_cache']
json_data = results['cached_api_response_json_data']
# Schedule the next retrieve. It is possible for the first retrieve
# of the day (above) to be using data from a few days ago.
results = api_internal_cache_manager.schedule_refresh_of_api_internal_cache(
api_name='voterGuidesUpcoming',
election_id_list_serialized=election_id_list_serialized,
api_internal_cache=api_internal_cache,
)
# Add a log entry here
if not api_internal_cache_found:
results = voter_guides_upcoming_retrieve_for_api(google_civic_election_id_list=google_civic_election_id_list)
status += results['status']
json_data = results['json_data']
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_voter_guide.py",
"copies": "1",
"size": "20752",
"license": "mit",
"hash": -4363824848264682500,
"line_mean": 54.1914893617,
"line_max": 117,
"alpha_frac": 0.6957883577,
"autogenerated": false,
"ratio": 3.4081129906388568,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4603901348338857,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from apis_v1.controllers import voter_count
from ballot.controllers import choose_election_and_prepare_ballot_data,voter_ballot_items_retrieve_for_api, \
voter_ballot_list_retrieve_for_api
from ballot.models import BallotItemListManager, BallotReturnedManager, find_best_previously_stored_ballot_returned, \
OFFICE, CANDIDATE, MEASURE, VoterBallotSavedManager
from bookmark.controllers import voter_all_bookmarks_status_retrieve_for_api, voter_bookmark_off_save_for_api, \
voter_bookmark_on_save_for_api, voter_bookmark_status_retrieve_for_api
from config.base import get_environment_variable
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django_user_agents.utils import get_user_agent
from email_outbound.controllers import voter_email_address_save_for_api, voter_email_address_retrieve_for_api, \
voter_email_address_sign_in_for_api, voter_email_address_verify_for_api
from email_outbound.models import EmailAddress, EmailManager
from wevote_functions.functions import extract_first_name_from_full_name, extract_last_name_from_full_name
from follow.controllers import voter_issue_follow_for_api
from geoip.controllers import voter_location_retrieve_from_ip_for_api
from image.controllers import TWITTER, FACEBOOK, cache_master_and_resized_image, create_resized_images
from import_export_ballotpedia.controllers import voter_ballot_items_retrieve_from_ballotpedia_for_api_v4
from import_export_facebook.controllers import voter_facebook_sign_in_retrieve_for_api, \
voter_facebook_sign_in_save_for_api
from import_export_google_civic.controllers import voter_ballot_items_retrieve_from_google_civic_for_api
from import_export_twitter.controllers import voter_twitter_save_to_current_account_for_api
import json
from organization.models import OrganizationManager
from position.controllers import voter_all_positions_retrieve_for_api, \
voter_position_retrieve_for_api, voter_position_comment_save_for_api, voter_position_visibility_save_for_api
from sms.controllers import voter_sms_phone_number_retrieve_for_api, voter_sms_phone_number_save_for_api
from sms.models import SMSManager
from support_oppose_deciding.controllers import voter_opposing_save, voter_stop_opposing_save, \
voter_stop_supporting_save, voter_supporting_save_for_api
from voter.controllers import voter_address_retrieve_for_api, voter_create_for_api, voter_merge_two_accounts_for_api, \
voter_merge_two_accounts_action, voter_photo_save_for_api, voter_retrieve_for_api, \
voter_save_photo_from_file_reader, voter_sign_out_for_api, voter_split_into_two_accounts_for_api
from voter.models import BALLOT_ADDRESS, fetch_voter_we_vote_id_from_voter_device_link, \
PROFILE_IMAGE_TYPE_FACEBOOK, PROFILE_IMAGE_TYPE_TWITTER, PROFILE_IMAGE_TYPE_UNKNOWN, PROFILE_IMAGE_TYPE_UPLOADED, \
VoterAddress, VoterAddressManager, VoterDeviceLink, VoterDeviceLinkManager, VoterManager, Voter, \
voter_has_authority
from voter_guide.controllers import voter_follow_all_organizations_followed_by_organization_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_maximum_number_to_retrieve_from_request, \
get_voter_device_id, is_voter_device_id_valid, positive_value_exists
from apis_v1.views import views_voter_utils
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def voter_address_retrieve_view(request): # voterAddressRetrieve
"""
Retrieve an address for this voter so we can figure out which ballot to display
:param request:
:return:
"""
voter_address_manager = VoterAddressManager()
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
else:
voter_device_link = VoterDeviceLink()
voter_id = 0
guess_if_no_address_saved = request.GET.get('guess_if_no_address_saved', True)
if guess_if_no_address_saved == 'false':
guess_if_no_address_saved = False
elif guess_if_no_address_saved == 'False':
guess_if_no_address_saved = False
elif guess_if_no_address_saved == '0':
guess_if_no_address_saved = False
status = ''
voter_address_retrieve_results = voter_address_retrieve_for_api(voter_device_id)
if voter_address_retrieve_results['address_found']:
status += voter_address_retrieve_results['status']
if positive_value_exists(voter_address_retrieve_results['google_civic_election_id']):
google_civic_election_id = voter_address_retrieve_results['google_civic_election_id']
else:
# This block of code helps us if the google_civic_election_id hasn't been saved in the voter_address table
# We retrieve voter_device_link
google_civic_election_id = 0
# Retrieve the voter_address
voter_address_results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id,
voter_address)
status += results['status']
if results['voter_ballot_saved_found']:
google_civic_election_id = results['google_civic_election_id']
json_data = {
'voter_device_id': voter_address_retrieve_results['voter_device_id'],
'address_type': voter_address_retrieve_results['address_type'],
'text_for_map_search': voter_address_retrieve_results['text_for_map_search'],
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': voter_address_retrieve_results['ballot_location_display_name'],
'ballot_returned_we_vote_id': voter_address_retrieve_results['ballot_returned_we_vote_id'],
'voter_entered_address': voter_address_retrieve_results['voter_entered_address'],
'voter_specific_ballot_from_google_civic':
voter_address_retrieve_results['voter_specific_ballot_from_google_civic'],
'latitude': voter_address_retrieve_results['latitude'],
'longitude': voter_address_retrieve_results['longitude'],
'normalized_line1': voter_address_retrieve_results['normalized_line1'],
'normalized_line2': voter_address_retrieve_results['normalized_line2'],
'normalized_city': voter_address_retrieve_results['normalized_city'],
'normalized_state': voter_address_retrieve_results['normalized_state'],
'normalized_zip': voter_address_retrieve_results['normalized_zip'],
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
status += voter_address_retrieve_results['status'] + ", "
# If we are here, then an address wasn't found, and we either want to return that info, or take a guess
# at the voter's location by looking it up by IP address
if not positive_value_exists(guess_if_no_address_saved):
# Do not guess at an address
status += 'DO_NOT_GUESS_IF_NO_ADDRESS_SAVED'
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': 0,
'ballot_location_display_name': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'ballot_returned_we_vote_id': '',
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
status += 'GUESS_IF_NO_ADDRESS_SAVED' + ", "
# If here, we are going to guess at the voter's location based on IP address
voter_location_results = voter_location_retrieve_from_ip_for_api(request)
# # TODO DALE TEMP
# voter_location_results['voter_location_found'] = True
# voter_location_results['voter_location'] = "New York, NY"
# voter_location_results['status'] = "TODO DALE Temp setting of voter_location to New York"
if voter_location_results['voter_location_found']:
status += 'VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_FOUND_FROM_IP '
# Since a new location was found, we need to save the address and then reach out to Google Civic
text_for_map_search = voter_location_results['voter_location']
status += '*** ' + text_for_map_search + ' ***, '
google_civic_election_id = 0
voter_address_save_results = voter_address_manager.update_or_create_voter_address(
voter_id, BALLOT_ADDRESS, text_for_map_search)
status += voter_address_save_results['status'] + ", "
if voter_address_save_results['success'] and voter_address_save_results['voter_address_found']:
voter_address = voter_address_save_results['voter_address']
use_test_election = False
# Reach out to Google and populate ballot items in the database with fresh ballot data
# NOTE: 2016-05-26 Google civic NEVER returns a ballot for City, State ZIP, so we could change this
# DALE 2018-09-06 TURNED OFF
# google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api(
# voter_device_id, text_for_map_search, use_test_election)
# status += google_retrieve_results['status'] + ", "
#
# if positive_value_exists(google_retrieve_results['google_civic_election_id']):
# # Update voter_address with the google_civic_election_id retrieved from Google Civic
# # and clear out ballot_saved information
# google_civic_election_id = google_retrieve_results['google_civic_election_id']
#
# voter_address.google_civic_election_id = google_civic_election_id
# voter_address_update_results = voter_address_manager.update_existing_voter_address_object(
# voter_address)
#
# if voter_address_update_results['success']:
# # Replace the former google_civic_election_id from this voter_device_link
# voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
# voter_device_id)
# if voter_device_link_results['voter_device_link_found']:
# voter_device_link = voter_device_link_results['voter_device_link']
# voter_device_link_manager.update_voter_device_link_with_election_id(
# voter_device_link, google_retrieve_results['google_civic_election_id'])
#
# else:
# # This block of code helps us if the google_civic_election_id wasn't found when we reached out
# # to the Google Civic API, following finding the voter's location from IP address.
# google_civic_election_id = 0
# We retrieve voter_device_link
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
else:
voter_device_link = VoterDeviceLink()
# Retrieve the voter_address
voter_address_results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id,
voter_address)
status += results['status']
if results['voter_ballot_saved_found']:
google_civic_election_id = results['google_civic_election_id']
voter_address_retrieve_results = voter_address_retrieve_for_api(voter_device_id)
status += voter_address_retrieve_results['status']
if voter_address_retrieve_results['address_found']:
json_data = {
'voter_device_id': voter_device_id,
'address_type': voter_address_retrieve_results['address_type'],
'text_for_map_search': voter_address_retrieve_results['text_for_map_search'],
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': voter_address_retrieve_results['ballot_location_display_name'],
'ballot_returned_we_vote_id': voter_address_retrieve_results['ballot_returned_we_vote_id'],
'voter_entered_address': voter_address_retrieve_results['voter_entered_address'],
'voter_specific_ballot_from_google_civic':
voter_address_retrieve_results['voter_specific_ballot_from_google_civic'],
'latitude': voter_address_retrieve_results['latitude'],
'longitude': voter_address_retrieve_results['longitude'],
'normalized_line1': voter_address_retrieve_results['normalized_line1'],
'normalized_line2': voter_address_retrieve_results['normalized_line2'],
'normalized_city': voter_address_retrieve_results['normalized_city'],
'normalized_state': voter_address_retrieve_results['normalized_state'],
'normalized_zip': voter_address_retrieve_results['normalized_zip'],
'success': voter_address_retrieve_results['success'],
'status': status,
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
else:
# Address not found from IP address
status += 'VOTER_ADDRESS_RETRIEVE_PART2_NO_ADDRESS'
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': '',
'ballot_returned_we_vote_id': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
status += 'VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_NOT_FOUND_FROM_IP: '
status += voter_location_results['status']
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': 0,
'ballot_location_display_name': '',
'ballot_returned_we_vote_id': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': False,
'status': status,
'address_found': False,
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_address_save_view(request): # voterAddressSave
"""
Save or update an address for this voter. Once the address is saved, update the ballot information.
:param request:
:return:
"""
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
simple_save = positive_value_exists(request.GET.get('simple_save', False))
ballot_location_display_name = ''
ballot_returned_we_vote_id = ''
text_for_map_search_saved = ''
substituted_address_nearby = False
voter_entered_address = True
voter_specific_ballot_from_google_civic = False
status = ""
success = True
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
try:
text_for_map_search = request.GET['text_for_map_search']
text_for_map_search = text_for_map_search.strip()
address_variable_exists = True
except KeyError:
text_for_map_search = ''
address_variable_exists = False
device_id_results = is_voter_device_id_valid(voter_device_id)
if not device_id_results['success']:
status += device_id_results['status']
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if not address_variable_exists:
status += "MISSING_GET_VARIABLE-ADDRESS "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# We retrieve voter_device_link
voter_ballot_saved_manager = VoterBallotSavedManager()
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
else:
status += "VOTER_DEVICE_LINK_NOT_FOUND_FROM_DEVICE_ID "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if not positive_value_exists(voter_id):
status += "VOTER_NOT_FOUND_FROM_DEVICE_ID-VOTER_ADDRESS_SAVE "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# Save the address value, and clear out ballot_saved information
voter_address_manager = VoterAddressManager()
voter_address_save_results = voter_address_manager.update_or_create_voter_address(
voter_id, BALLOT_ADDRESS, text_for_map_search, google_civic_election_id, voter_entered_address)
# TODO DALE 2017-07-17 This needs a fresh look:
# , google_civic_election_id
status += voter_address_save_results['status']
# If simple_save is passed in only save address and then send response (you must pass in a google_civic_election_id)
if positive_value_exists(simple_save) and positive_value_exists(google_civic_election_id):
success = voter_address_save_results['success'] and voter_address_save_results['voter_address_found']
status += "SIMPLE_ADDRESS_SAVE "
json_data = {
'status': status,
'success': success,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
'google_civic_election_id': google_civic_election_id
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if voter_address_save_results['success'] and voter_address_save_results['voter_address_found']:
# # Remove the former google_civic_election_id from this voter_device_id
# voter_device_link_manager.update_voter_device_link_with_election_id(voter_device_link, 0)
voter_address = voter_address_save_results['voter_address']
use_test_election = False
turn_off_direct_voter_ballot_retrieve = False # Search for this variable elsewhere
default_election_data_source_is_ballotpedia = True
if positive_value_exists(simple_save):
# Do not retrieve / return a ballot
pass
elif turn_off_direct_voter_ballot_retrieve:
# We set this option when we want to force the retrieval of a nearby ballot
pass
elif default_election_data_source_is_ballotpedia:
status += "VOTER_ADDRESS_SAVE-SHOULD_WE_USE_BALLOTPEDIA_API? "
length_at_which_we_suspect_address_has_street = 25
length_of_text_for_map_search = 0
if isinstance(text_for_map_search, str):
length_of_text_for_map_search = len(text_for_map_search)
was_refreshed_from_ballotpedia_just_now = False
# We don't want to call Ballotpedia when we just have "City, State ZIP". Since we don't always know
# whether we have a street address or not, then we use a simple string length cut-off.
if length_of_text_for_map_search > length_at_which_we_suspect_address_has_street:
status += "TEXT_FOR_MAP_SEARCH_LONG_ENOUGH "
# 1a) Get ballot data from Ballotpedia for the actual VoterAddress
ballotpedia_retrieve_results = voter_ballot_items_retrieve_from_ballotpedia_for_api_v4(
voter_device_id,
text_for_map_search=text_for_map_search,
google_civic_election_id=google_civic_election_id)
status += ballotpedia_retrieve_results['status']
if ballotpedia_retrieve_results['google_civic_election_id'] \
and ballotpedia_retrieve_results['ballot_returned_found']:
was_refreshed_from_ballotpedia_just_now = True
is_from_substituted_address = False
substituted_address_nearby = ''
is_from_test_address = False
polling_location_we_vote_id_source = '' # Not used when retrieving directly for the voter
# These variables are needed below
ballot_location_display_name = ballotpedia_retrieve_results['ballot_location_display_name']
ballot_returned_we_vote_id = ballotpedia_retrieve_results['ballot_returned_we_vote_id']
# We update the voter_address with this google_civic_election_id outside of this function
# Save the meta information for this ballot data
save_results = voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id=voter_id,
google_civic_election_id=ballotpedia_retrieve_results['google_civic_election_id'],
state_code=ballotpedia_retrieve_results['state_code'],
election_day_text=ballotpedia_retrieve_results['election_day_text'],
election_description_text=ballotpedia_retrieve_results['election_description_text'],
original_text_for_map_search=ballotpedia_retrieve_results['text_for_map_search'],
substituted_address_nearby=substituted_address_nearby,
is_from_substituted_address=is_from_substituted_address,
is_from_test_ballot=is_from_test_address,
polling_location_we_vote_id_source=polling_location_we_vote_id_source,
ballot_location_display_name=ballotpedia_retrieve_results['ballot_location_display_name'],
ballot_returned_we_vote_id=ballotpedia_retrieve_results['ballot_returned_we_vote_id'],
ballot_location_shortcut=ballotpedia_retrieve_results['ballot_location_shortcut'],
original_text_city=ballotpedia_retrieve_results['original_text_city'],
original_text_state=ballotpedia_retrieve_results['original_text_state'],
original_text_zip=ballotpedia_retrieve_results['original_text_zip'],
)
status += save_results['status']
google_civic_election_id = ballotpedia_retrieve_results['google_civic_election_id']
else:
status += "NOT_REACHING_OUT_TO_BALLOTPEDIA "
if not was_refreshed_from_ballotpedia_just_now:
# 2) Find ballot data previously stored from a nearby address
ballot_returned_results = find_best_previously_stored_ballot_returned(voter_id, text_for_map_search)
status += ballot_returned_results['status']
if ballot_returned_results['ballot_returned_found']:
# If this ballot_returned entry is the result of searching based on an address, as opposed to
# a specific_ballot_requested, we want to update the VoterAddress
if positive_value_exists(voter_address.text_for_map_search):
try:
voter_address.ballot_location_display_name = \
ballot_returned_results['ballot_location_display_name']
voter_address.ballot_returned_we_vote_id = \
ballot_returned_results['ballot_returned_we_vote_id']
voter_address.save()
except Exception as e:
status += "COULD_NOT_SAVE_VOTER_ADDRESS: " + str(e) + " "
ballot_returned_we_vote_id = ballot_returned_results['ballot_returned_we_vote_id']
google_civic_election_id = ballot_returned_results['google_civic_election_id']
if positive_value_exists(google_civic_election_id) and positive_value_exists(voter_id):
# Delete voter-specific ballot_returned for this election
ballot_returned_manager = BallotReturnedManager()
results = ballot_returned_manager.delete_ballot_returned_by_identifier(
voter_id=voter_id,
google_civic_election_id=google_civic_election_id)
# Delete voter_ballot_saved for this election
voter_ballot_saved_manager = VoterBallotSavedManager()
voter_ballot_saved_manager.delete_voter_ballot_saved(
voter_id=voter_id, google_civic_election_id=google_civic_election_id)
# Delete all existing voter-specific ballot items for this election
ballot_item_list_manager = BallotItemListManager()
ballot_item_list_manager.delete_all_ballot_items_for_voter(voter_id, google_civic_election_id)
# And now store the details of this ballot for this voter
is_from_substituted_address = True
is_from_test_address = False
save_results = voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id=voter_id,
google_civic_election_id=ballot_returned_results['google_civic_election_id'],
state_code=ballot_returned_results['state_code'],
election_day_text=ballot_returned_results['election_day_text'],
election_description_text=ballot_returned_results['election_description_text'],
original_text_for_map_search=text_for_map_search,
substituted_address_nearby=ballot_returned_results['substituted_address_nearby'],
is_from_substituted_address=is_from_substituted_address,
is_from_test_ballot=is_from_test_address,
polling_location_we_vote_id_source=ballot_returned_results[
'polling_location_we_vote_id_source'],
ballot_location_display_name=ballot_returned_results['ballot_location_display_name'],
ballot_returned_we_vote_id=ballot_returned_results['ballot_returned_we_vote_id'],
ballot_location_shortcut=ballot_returned_results['ballot_location_shortcut'],
substituted_address_city=ballot_returned_results['original_text_city'],
substituted_address_state=ballot_returned_results['original_text_state'],
substituted_address_zip=ballot_returned_results['original_text_zip'],
)
status += save_results['status']
else:
# Reach out to Google and populate ballot items in the database with fresh ballot data
google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api( # DEBUG=1
voter_device_id, text_for_map_search, use_test_election)
# Update voter_address with the google_civic_election_id retrieved from Google Civic
# and clear out ballot_saved information IFF we got a valid google_civic_election_id back
if google_retrieve_results['google_civic_election_id']:
google_civic_election_id = convert_to_int(google_retrieve_results['google_civic_election_id'])
else:
# Leave google_civic_election_id as it was at the top of this function
pass
if google_retrieve_results['ballot_location_display_name']:
ballot_location_display_name = google_retrieve_results['ballot_location_display_name']
if google_retrieve_results['ballot_returned_we_vote_id']:
ballot_returned_we_vote_id = google_retrieve_results['ballot_returned_we_vote_id']
# At this point proceed to update google_civic_election_id whether it is a positive integer or zero
# First retrieve the latest address, since it gets saved when we retrieve from google civic
updated_address_results = voter_address_manager.retrieve_address(voter_address.id)
if updated_address_results['voter_address_found']:
voter_address = updated_address_results['voter_address']
voter_address.google_civic_election_id = google_civic_election_id
voter_address.ballot_location_display_name = ballot_location_display_name
voter_address.ballot_returned_we_vote_id = ballot_returned_we_vote_id
voter_entered_address = voter_address.voter_entered_address
voter_specific_ballot_from_google_civic = voter_address.refreshed_from_google
voter_address_update_results = voter_address_manager.update_existing_voter_address_object(voter_address)
status += voter_address_update_results['status']
if voter_address_update_results['success']:
# Replace the former google_civic_election_id from this voter_device_link
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_device_link_manager.update_voter_device_link_with_election_id(
voter_device_link, google_civic_election_id)
if voter_address_update_results['voter_address_found']:
voter_address = voter_address_update_results['voter_address']
text_for_map_search_saved = voter_address.text_for_map_search
if positive_value_exists(simple_save):
# Do not retrieve / return a ballot
json_data = {
'status': status,
'success': success,
'google_civic_election_id': google_civic_election_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
'substituted_address_nearby': substituted_address_nearby,
'ballot_found': False,
'ballot_caveat': None,
'is_from_substituted_address': None,
'is_from_test_ballot': None,
'ballot_item_list': [],
}
else:
# This does return the data twice, since the WebApp requests
# voterBallotItemRetrieve when voterAddressSave completes
json_data = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id,
ballot_returned_we_vote_id)
json_data['simple_save'] = simple_save
json_data['address'] = {
'text_for_map_search': text_for_map_search_saved,
'google_civic_election_id': google_civic_election_id,
'ballot_returned_we_vote_id': ballot_returned_we_vote_id,
'ballot_location_display_name': ballot_location_display_name,
'voter_entered_address': voter_entered_address,
'voter_specific_ballot_from_google_civic': voter_specific_ballot_from_google_civic,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_ballot_items_retrieve_view(request): # voterBallotItemsRetrieve
"""
Request the ballot data requested by the voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# If passed in, we want to look at
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
ballot_returned_we_vote_id = request.GET.get('ballot_returned_we_vote_id', '')
ballot_location_shortcut = request.GET.get('ballot_location_shortcut', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
if use_test_election:
google_civic_election_id = 2000 # The Google Civic test election
json_data = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id,
ballot_returned_we_vote_id, ballot_location_shortcut)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_ballot_items_retrieve_from_google_civic_view(request): # voterBallotItemsRetrieveFromGoogleCivic
voter_device_id = get_voter_device_id(request)
text_for_map_search = request.GET.get('text_for_map_search', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
voter_id = 0
original_text_city = ''
original_text_state = ''
original_text_zip = ''
google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api(
voter_device_id, text_for_map_search, use_test_election)
if google_retrieve_results['google_civic_election_id'] and not use_test_election:
# After the ballot is retrieved from google we want to save some info about it for the voter
if positive_value_exists(voter_device_id):
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
if positive_value_exists(google_retrieve_results['ballot_returned_we_vote_id']):
ballot_returned = google_retrieve_results['ballot_returned']
original_text_city = ballot_returned.normalized_city
original_text_state = ballot_returned.normalized_state
original_text_zip = ballot_returned.normalized_zip
if positive_value_exists(voter_id):
voter_ballot_saved_manager = VoterBallotSavedManager()
is_from_substituted_address = False
substituted_address_nearby = ''
is_from_test_address = False
polling_location_we_vote_id_source = "" # Not used when retrieving directly from Google Civic
# We don't update the voter_address because this view might be used independent of the voter_address
# Save the meta information for this ballot data. If it fails, ignore the failure
voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id,
google_retrieve_results['google_civic_election_id'],
google_retrieve_results['state_code'],
google_retrieve_results['election_day_text'],
google_retrieve_results['election_description_text'],
google_retrieve_results['text_for_map_search'],
substituted_address_nearby,
is_from_substituted_address,
is_from_test_address,
polling_location_we_vote_id_source,
google_retrieve_results['ballot_location_display_name'],
google_retrieve_results['ballot_returned_we_vote_id'],
google_retrieve_results['ballot_location_shortcut'],
original_text_city=original_text_city,
original_text_state=original_text_state,
original_text_zip=original_text_zip,
)
return HttpResponse(json.dumps(google_retrieve_results), content_type='application/json')
def voter_ballot_list_retrieve_view(request): # voterBallotListRetrieve
"""
(voterBallotListRetrieve) Retrieve a list of election ballots per voter_id.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_id = 0
if positive_value_exists(voter_device_id):
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
voter_device_link = voter_device_link_results['voter_device_link']
if voter_device_link_results['voter_device_link_found']:
voter_id = voter_device_link.voter_id
if not positive_value_exists(voter_id):
json_data = {
'status': "VOTER_ID_MISSING",
'success': False,
'voter_device_id': voter_device_id,
'voter_ballot_list_found': False,
'voter_ballot_list': [],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_ballot_list_retrieve_for_api(voter_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_ballot_list_found': results['voter_ballot_list_found'],
'voter_ballot_list': results['voter_ballot_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_count_view(request): # voterCountView
return voter_count()
def voter_create_view(request): # voterCreate
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return voter_create_for_api(voter_device_id)
def voter_create_new_account_view(request): # voterCreateNewAccount
authority_required = {'admin'}
status = ""
if voter_has_authority(request, authority_required):
# voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
first_name = request.GET.get('firstname', '')
last_name = request.GET.get('lastname', '')
email = request.GET.get('email', '')
password = request.GET.get('password', '')
is_admin = request.GET.get('is_admin', False) == 'true'
is_analytics_admin = request.GET.get('is_analytics_admin', False) == 'true'
is_partner_organization = request.GET.get('is_partner_organization', False) == 'true'
is_political_data_manager = request.GET.get('is_political_data_manager', False) == 'true'
is_political_data_viewer = request.GET.get('is_political_data_viewer', False) == 'true'
is_verified_volunteer = request.GET.get('is_verified_volunteer', False) == 'true'
# Check to make sure email isn't attached to existing account in EmailAddress table
email_address_queryset = EmailAddress.objects.all()
email_address_queryset = email_address_queryset.filter(
normalized_email_address__iexact=email,
deleted=False
)
email_address_list = list(email_address_queryset)
email_already_in_use = True if len(email_address_list) > 0 else False
if email_already_in_use:
status += "EMAIL_ADDRESS_ALREADY_IN_USE "
json_data = {
'status': status,
'success': False,
'duplicate_email': True,
'has_permission': True,
}
else:
results = Voter.objects.create_new_voter_account(
first_name, last_name, email, password, is_admin, is_analytics_admin, is_partner_organization,
is_political_data_manager, is_political_data_viewer, is_verified_volunteer)
json_data = {
'status': results['status'],
'success': results['success'],
'duplicate_email': results['duplicate_email'],
'has_permission': True,
}
else:
json_data = {
'status': "Insufficient rights to add user",
'success': True,
'duplicate_email': False,
'has_permission': False,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_retrieve_view(request): # voterEmailAddressRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_email_address_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_address_list_found': results['email_address_list_found'],
'email_address_list': results['email_address_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_save_view(request): # voterEmailAddressSave
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
text_for_email_address = request.GET.get('text_for_email_address', '')
incoming_email_we_vote_id = request.GET.get('email_we_vote_id', '')
resend_verification_email = positive_value_exists(request.GET.get('resend_verification_email', False))
resend_verification_code_email = positive_value_exists(request.GET.get('resend_verification_code_email', False))
send_link_to_sign_in = positive_value_exists(request.GET.get('send_link_to_sign_in', False))
send_sign_in_code_email = positive_value_exists(request.GET.get('send_sign_in_code_email', False))
make_primary_email = positive_value_exists(request.GET.get('make_primary_email', False))
delete_email = positive_value_exists(request.GET.get('delete_email', ""))
is_cordova = positive_value_exists(request.GET.get('is_cordova', False))
hostname = request.GET.get('hostname', '')
results = voter_email_address_save_for_api(
voter_device_id=voter_device_id,
text_for_email_address=text_for_email_address,
incoming_email_we_vote_id=incoming_email_we_vote_id,
send_link_to_sign_in=send_link_to_sign_in,
send_sign_in_code_email=send_sign_in_code_email,
resend_verification_email=resend_verification_email,
resend_verification_code_email=resend_verification_code_email,
make_primary_email=make_primary_email,
delete_email=delete_email,
is_cordova=is_cordova,
web_app_root_url=hostname,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'text_for_email_address': text_for_email_address,
'make_primary_email': make_primary_email,
'delete_email': delete_email,
'email_address_we_vote_id': results['email_address_we_vote_id'],
'email_address_saved_we_vote_id': results['email_address_saved_we_vote_id'],
'email_address_already_owned_by_other_voter': results['email_address_already_owned_by_other_voter'],
'email_address_already_owned_by_this_voter': results['email_address_already_owned_by_this_voter'],
'email_address_created': results['email_address_created'],
'email_address_not_valid': results['email_address_not_valid'],
'email_address_deleted': results['email_address_deleted'],
'verification_email_sent': results['verification_email_sent'],
'link_to_sign_in_email_sent': results['link_to_sign_in_email_sent'],
'sign_in_code_email_sent': results['sign_in_code_email_sent'],
'email_address_found': results['email_address_found'],
'email_address_list_found': results['email_address_list_found'],
'email_address_list': results['email_address_list'],
'secret_code_system_locked_for_this_voter_device_id':
results['secret_code_system_locked_for_this_voter_device_id'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_sign_in_view(request): # voterEmailAddressSignIn
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
yes_please_merge_accounts = request.GET.get('yes_please_merge_accounts', '')
yes_please_merge_accounts = positive_value_exists(yes_please_merge_accounts)
results = voter_email_address_sign_in_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_ownership_is_verified': results['email_ownership_is_verified'],
'email_secret_key_belongs_to_this_voter': results['email_secret_key_belongs_to_this_voter'],
'email_sign_in_attempted': True,
'email_address_found': results['email_address_found'],
'yes_please_merge_accounts': yes_please_merge_accounts,
'voter_we_vote_id_from_secret_key': results['voter_we_vote_id_from_secret_key'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_verify_view(request): # voterEmailAddressVerify
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
results = voter_email_address_verify_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_ownership_is_verified': results['email_ownership_is_verified'],
'email_secret_key_belongs_to_this_voter': results['email_secret_key_belongs_to_this_voter'],
'email_verify_attempted': True,
'email_address_found': results['email_address_found'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_facebook_sign_in_retrieve_view(request): # voterFacebookSignInRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_facebook_sign_in_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'existing_facebook_account_found': results['existing_facebook_account_found'],
'voter_we_vote_id_attached_to_facebook': results['voter_we_vote_id_attached_to_facebook'],
'voter_we_vote_id_attached_to_facebook_email': results['voter_we_vote_id_attached_to_facebook_email'],
'facebook_retrieve_attempted': True,
'facebook_sign_in_found': results['facebook_sign_in_found'],
'facebook_sign_in_verified': results['facebook_sign_in_verified'],
'facebook_sign_in_failed': results['facebook_sign_in_failed'],
'facebook_secret_key': results['facebook_secret_key'],
'voter_has_data_to_preserve': results['voter_has_data_to_preserve'],
'facebook_user_id': results['facebook_user_id'],
'facebook_profile_image_url_https': results['facebook_profile_image_url_https'],
'we_vote_hosted_profile_image_url_large': results['we_vote_hosted_profile_image_url_large'],
'we_vote_hosted_profile_image_url_medium': results['we_vote_hosted_profile_image_url_medium'],
'we_vote_hosted_profile_image_url_tiny': results['we_vote_hosted_profile_image_url_tiny']
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_facebook_sign_in_save_view(request): # voterFacebookSignInSave
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
save_auth_data = request.GET.get('save_auth_data', False)
save_auth_data = positive_value_exists(save_auth_data)
facebook_access_token = request.GET.get('facebook_access_token', '')
facebook_user_id = request.GET.get('facebook_user_id', '')
facebook_expires_in = request.GET.get('facebook_expires_in', 0)
facebook_signed_request = request.GET.get('facebook_signed_request', '')
save_profile_data = request.GET.get('save_profile_data', False)
save_profile_data = positive_value_exists(save_profile_data)
save_photo_data = request.GET.get('save_photo_data', False)
save_photo_data = positive_value_exists(save_photo_data)
facebook_email = request.GET.get('facebook_email', '')
facebook_first_name = request.GET.get('facebook_first_name', '')
facebook_middle_name = request.GET.get('facebook_middle_name', '')
facebook_last_name = request.GET.get('facebook_last_name', '')
facebook_profile_image_url_https = request.GET.get('facebook_profile_image_url_https', '')
facebook_background_image_url_https = request.GET.get('facebook_background_image_url_https', '')
facebook_background_image_offset_x = request.GET.get('facebook_background_image_offset_x', '')
facebook_background_image_offset_y = request.GET.get('facebook_background_image_offset_y', '')
results = voter_facebook_sign_in_save_for_api(
voter_device_id=voter_device_id,
save_auth_data=save_auth_data,
facebook_access_token=facebook_access_token,
facebook_user_id=facebook_user_id,
facebook_expires_in=facebook_expires_in,
facebook_signed_request=facebook_signed_request,
save_profile_data=save_profile_data,
facebook_email=facebook_email,
facebook_first_name=facebook_first_name,
facebook_middle_name=facebook_middle_name,
facebook_last_name=facebook_last_name,
save_photo_data=save_photo_data,
facebook_profile_image_url_https=facebook_profile_image_url_https,
facebook_background_image_url_https=facebook_background_image_url_https,
facebook_background_image_offset_x=facebook_background_image_offset_x,
facebook_background_image_offset_y=facebook_background_image_offset_y,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_save_attempted': True,
'facebook_sign_in_saved': results['facebook_sign_in_saved'],
'save_auth_data': save_auth_data,
'save_profile_data': save_profile_data,
'save_photo_data': save_photo_data,
'minimum_data_saved': results['minimum_data_saved'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_follow_all_organizations_followed_by_organization_view(request):
# voterFollowAllOrganizationsFollowedByOrganization
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_follow = get_maximum_number_to_retrieve_from_request(request)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
return voter_follow_all_organizations_followed_by_organization_for_api(
voter_device_id,
organization_we_vote_id=organization_we_vote_id,
maximum_number_to_follow=maximum_number_to_follow, user_agent_string=user_agent_string,
user_agent_object=user_agent_object)
def voter_issue_follow_view(request): # issueFollow
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
issue_we_vote_id = request.GET.get('issue_we_vote_id', False)
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
follow_value = positive_value_exists(request.GET.get('follow', False))
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
ignore_value = positive_value_exists(request.GET.get('ignore', False))
result = voter_issue_follow_for_api(voter_device_id=voter_device_id,
issue_we_vote_id=issue_we_vote_id,
follow_value=follow_value,
ignore_value=ignore_value, user_agent_string=user_agent_string,
user_agent_object=user_agent_object)
result['google_civic_election_id'] = google_civic_election_id
return HttpResponse(json.dumps(result), content_type='application/json')
def voter_location_retrieve_from_ip_view(request): # voterLocationRetrieveFromIP - GeoIP geo location
"""
Take the IP address and return a location (voterLocationRetrieveFromIP)
:param request:
:return:
"""
ip_address = request.GET.get('ip_address', '')
voter_location_results = voter_location_retrieve_from_ip_for_api(request, ip_address)
json_data = {
'success': voter_location_results['success'],
'status': voter_location_results['status'],
'voter_location_found': voter_location_results['voter_location_found'],
'voter_location': voter_location_results['voter_location'],
'ip_address': voter_location_results['ip_address'],
'x_forwarded_for': voter_location_results['x_forwarded_for'],
'http_x_forwarded_for': voter_location_results['http_x_forwarded_for'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_merge_two_accounts_view(request): # voterMergeTwoAccounts
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
facebook_secret_key = request.GET.get('facebook_secret_key', '')
twitter_secret_key = request.GET.get('twitter_secret_key', '')
invitation_secret_key = request.GET.get('invitation_secret_key', '')
hostname = request.GET.get('hostname', '')
results = voter_merge_two_accounts_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key,
facebook_secret_key=facebook_secret_key,
twitter_secret_key=twitter_secret_key,
invitation_secret_key=invitation_secret_key,
web_app_root_url=hostname)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_photo_save_view(request): # voterPhotoSave
"""
Save or update a photo for this voter
:param request:
:return:
"""
status = ''
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
try:
facebook_profile_image_url_https = request.GET['facebook_profile_image_url_https']
facebook_profile_image_url_https = facebook_profile_image_url_https.strip()
facebook_photo_variable_exists = True
except KeyError:
facebook_profile_image_url_https = ''
facebook_photo_variable_exists = False
results = voter_photo_save_for_api(voter_device_id,
facebook_profile_image_url_https, facebook_photo_variable_exists)
voter_photo_saved = True if results['success'] else False
if not positive_value_exists(facebook_profile_image_url_https):
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'voter_photo_saved': voter_photo_saved,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
status += results['status'] + ", "
# If here, we saved a valid photo
json_data = {
'status': status,
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'voter_photo_saved': voter_photo_saved,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
def voter_plan_list_retrieve_view(request): # voterPlanListRetrieve
"""
Retrieve voter plans so we can show off examples from other voters
:param request:
:return:
"""
status = ''
voter_plan_list = []
voter_manager = VoterManager()
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
results = voter_manager.retrieve_voter_plan_list(google_civic_election_id=google_civic_election_id)
if not results['success']:
status += results['status']
status += "RETRIEVE_VOTER_PLAN_LIST_FAILED "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
modified_voter_plan_list = []
voter_plan_list = results['voter_plan_list']
for voter_plan in voter_plan_list:
voter_plan_dict = {
'date_entered': voter_plan.date_entered.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': voter_plan.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'google_civic_election_id': voter_plan.google_civic_election_id,
'show_to_public': voter_plan.show_to_public,
'state_code': voter_plan.state_code,
'voter_plan_data_serialized': voter_plan.voter_plan_data_serialized,
'voter_plan_text': voter_plan.voter_plan_text,
'voter_we_vote_id': voter_plan.voter_we_vote_id,
}
modified_voter_plan_list.append(voter_plan_dict)
json_data = {
'status': status,
'success': True,
'voter_plan_list': modified_voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_plans_for_voter_retrieve_view(request): # voterPlansForVoterRetrieve
"""
Retrieve all voter plans for signed in voter
:param request:
:return:
"""
status = ''
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
voter_plan_list = []
voter_manager = VoterManager()
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if not positive_value_exists(voter_we_vote_id):
status += "VOTER_PLANS_RETRIEVE_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_manager.retrieve_voter_plan_list(voter_we_vote_id=voter_we_vote_id)
if not results['success']:
status += results['status']
status += "RETRIEVE_VOTER_PLAN_LIST_FAILED "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
modified_voter_plan_list = []
voter_plan_list = results['voter_plan_list']
for voter_plan in voter_plan_list:
voter_plan_dict = {
'date_entered': voter_plan.date_entered.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': voter_plan.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'google_civic_election_id': voter_plan.google_civic_election_id,
'show_to_public': voter_plan.show_to_public,
'state_code': voter_plan.state_code,
'voter_plan_data_serialized': voter_plan.voter_plan_data_serialized,
'voter_plan_text': voter_plan.voter_plan_text,
'voter_we_vote_id': voter_plan.voter_we_vote_id,
}
modified_voter_plan_list.append(voter_plan_dict)
json_data = {
'status': status,
'success': True,
'voter_plan_list': modified_voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_plan_save_view(request): # voterPlanSave
"""
Save current voter plan for this voter
:param request:
:return:
"""
status = ''
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
show_to_public = positive_value_exists(request.GET.get('show_to_public', False))
state_code = request.GET.get('state_code', '')
voter_plan_data_serialized = request.GET.get('voter_plan_data_serialized', '')
# voter_plan_data_serialized = json.loads(voter_plan_data_serialized) # Leave as a string
voter_plan_text = request.GET.get('voter_plan_text', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_we_vote_id = ''
voter_plan_list = []
voter_manager = VoterManager()
if positive_value_exists(voter_device_id):
voter_we_vote_id = fetch_voter_we_vote_id_from_voter_device_link(voter_device_id)
if not positive_value_exists(voter_we_vote_id):
status += "VOTER_PLAN_SAVE_MISSING_VOTER_WE_VOTE_ID "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if not positive_value_exists(google_civic_election_id):
status += "VOTER_PLAN_SAVE_MISSING_GOOGLE_CIVIC_ELECTION_ID "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_manager.update_or_create_voter_plan(
voter_we_vote_id=voter_we_vote_id,
google_civic_election_id=google_civic_election_id,
show_to_public=show_to_public,
state_code=state_code,
voter_plan_data_serialized=voter_plan_data_serialized,
voter_plan_text=voter_plan_text,
)
if not results['success']:
status += results['status']
status += "COULD_NOT_SAVE_VOTER_PLAN "
results = voter_manager.retrieve_voter_plan_list(voter_we_vote_id=voter_we_vote_id)
if not results['success']:
status += results['status']
status += "RETRIEVE_VOTER_PLAN_LIST_FAILED "
json_data = {
'status': status,
'success': False,
'voter_plan_list': voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
modified_voter_plan_list = []
voter_plan_list = results['voter_plan_list']
for voter_plan in voter_plan_list:
voter_plan_dict = {
'date_entered': voter_plan.date_entered.strftime('%Y-%m-%d %H:%M:%S'),
'date_last_changed': voter_plan.date_last_changed.strftime('%Y-%m-%d %H:%M:%S'),
'google_civic_election_id': voter_plan.google_civic_election_id,
'show_to_public': voter_plan.show_to_public,
'state_code': voter_plan.state_code,
'voter_plan_data_serialized': voter_plan.voter_plan_data_serialized,
'voter_plan_text': voter_plan.voter_plan_text,
'voter_we_vote_id': voter_plan.voter_we_vote_id,
}
modified_voter_plan_list.append(voter_plan_dict)
json_data = {
'status': status,
'success': True,
'voter_plan_list': modified_voter_plan_list,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_position_retrieve_view(request):
"""
Retrieve all of the details about a single position based on unique identifier. voterPositionRetrieve
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
# ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_we_vote_id = ballot_item_we_vote_id
candidate_we_vote_id = ''
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_we_vote_id = ''
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_we_vote_id = ''
candidate_we_vote_id = ''
measure_we_vote_id = ballot_item_we_vote_id
else:
office_we_vote_id = ''
candidate_we_vote_id = ''
measure_we_vote_id = ''
return voter_position_retrieve_for_api(
voter_device_id=voter_device_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id
)
def voter_position_visibility_save_view(request): # voterPositionVisibilitySave
"""
Change the visibility (between public vs. friends-only) for a single measure or candidate for one voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
visibility_setting = request.GET.get('visibility_setting', False)
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = None
office_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_we_vote_id = None
measure_we_vote_id = ballot_item_we_vote_id
office_we_vote_id = None
elif kind_of_ballot_item == OFFICE:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = ballot_item_we_vote_id
else:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = None
results = voter_position_visibility_save_for_api(
voter_device_id=voter_device_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
visibility_setting=visibility_setting,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_all_positions_retrieve_view(request): # voterAllPositionsRetrieve
"""
Retrieve a list of all positions for one voter, including "is_support", "is_oppose" and "statement_text".
Note that these can either be public positions or private positions.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
return voter_all_positions_retrieve_for_api(
voter_device_id=voter_device_id,
google_civic_election_id=google_civic_election_id
)
def voter_position_comment_save_view(request): # voterPositionCommentSave
"""
Save comment for a single measure or candidate for one voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_we_vote_id = request.GET.get('position_we_vote_id', "")
statement_text = request.GET.get('statement_text', False)
statement_html = request.GET.get('statement_html', False)
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = None
office_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_we_vote_id = None
measure_we_vote_id = ballot_item_we_vote_id
office_we_vote_id = None
elif kind_of_ballot_item == OFFICE:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = ballot_item_we_vote_id
else:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = None
results = voter_position_comment_save_for_api(
voter_device_id=voter_device_id,
position_we_vote_id=position_we_vote_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
statement_text=statement_text,
statement_html=statement_html,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_opposing_save_view(request):
"""
Save support for a single measure or candidate for one voter (voterOpposingSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_opposing_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_split_into_two_accounts_view(request): # voterSplitIntoTwoAccounts
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
split_off_twitter = request.GET.get('split_off_twitter', True) # We want to break off the Twitter from this account
results = voter_split_into_two_accounts_for_api(voter_device_id=voter_device_id,
split_off_twitter=split_off_twitter)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_retrieve_view(request): # voterRetrieve
"""
Retrieve a single voter based on voter_device
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
# Figure out the city & state from IP address
voter_location_results = voter_location_retrieve_from_ip_for_api(request)
state_code_from_ip_address = voter_location_results['region']
results = voter_retrieve_for_api(voter_device_id=voter_device_id,
state_code_from_ip_address=state_code_from_ip_address,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_sign_out_view(request): # voterSignOut
"""
Sign out from this device. (Delete this voter_device_id from the database, OR if sign_out_all_devices is True,
sign out from all devices.)
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
sign_out_all_devices = request.GET.get('sign_out_all_devices', 0)
if not positive_value_exists(voter_device_id):
success = False
status = "VOTER_SIGN_OUT_VOTER_DEVICE_ID_DOES_NOT_EXIST"
json_data = {
'voter_device_id': voter_device_id,
'sign_out_all_devices': sign_out_all_devices,
'success': success,
'status': status,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_sign_out_for_api(voter_device_id=voter_device_id, sign_out_all_devices=sign_out_all_devices)
json_data = {
'voter_device_id': voter_device_id,
'sign_out_all_devices': sign_out_all_devices,
'success': results['success'],
'status': results['status'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_sms_phone_number_retrieve_view(request): # voterSMSPhoneNumberRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_sms_phone_number_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'sms_phone_number_list_found': results['sms_phone_number_list_found'],
'sms_phone_number_list': results['sms_phone_number_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_sms_phone_number_save_view(request): # voterSMSPhoneNumberSave
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
sms_phone_number = request.GET.get('sms_phone_number', '')
incoming_sms_we_vote_id = request.GET.get('sms_we_vote_id', '')
resend_verification_sms = positive_value_exists(request.GET.get('resend_verification_sms', False))
send_sign_in_code_sms = positive_value_exists(request.GET.get('send_sign_in_code_sms', False))
make_primary_sms_phone_number = positive_value_exists(request.GET.get('make_primary_sms_phone_number', False))
delete_sms = positive_value_exists(request.GET.get('delete_sms', ""))
hostname = request.GET.get('hostname', '')
results = voter_sms_phone_number_save_for_api(
voter_device_id=voter_device_id,
sms_phone_number=sms_phone_number,
incoming_sms_we_vote_id=incoming_sms_we_vote_id,
send_sign_in_code_sms=send_sign_in_code_sms,
resend_verification_sms=resend_verification_sms,
make_primary_sms_phone_number=make_primary_sms_phone_number,
delete_sms=delete_sms,
web_app_root_url=hostname,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'sms_phone_number': sms_phone_number,
'make_primary_sms_phone_number': make_primary_sms_phone_number,
'delete_sms': delete_sms,
'sms_phone_number_we_vote_id': results['sms_phone_number_we_vote_id'],
'sms_phone_number_saved_we_vote_id': results['sms_phone_number_saved_we_vote_id'],
'sms_phone_number_already_owned_by_other_voter': results['sms_phone_number_already_owned_by_other_voter'],
'sms_phone_number_already_owned_by_this_voter': results['sms_phone_number_already_owned_by_this_voter'],
'sms_phone_number_created': results['sms_phone_number_created'],
'sms_phone_number_deleted': results['sms_phone_number_deleted'],
'verification_sms_sent': results['verification_sms_sent'],
'link_to_sign_in_sms_sent': results['link_to_sign_in_sms_sent'],
'sign_in_code_sms_sent': results['sign_in_code_sms_sent'],
'sms_phone_number_found': results['sms_phone_number_found'],
'sms_phone_number_list_found': results['sms_phone_number_list_found'],
'sms_phone_number_list': results['sms_phone_number_list'],
'secret_code_system_locked_for_this_voter_device_id':
results['secret_code_system_locked_for_this_voter_device_id'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_stop_opposing_save_view(request): # voterStopOpposingSave
"""
Save support for a single measure or candidate for one voter (voterStopOpposingSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_stop_opposing_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_stop_supporting_save_view(request): # voterStopSupportingSave
"""
Save support for a single measure or candidate for one voter (voterStopSupportingSave)
Default to set this as a position for your friends only.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_stop_supporting_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_supporting_save_view(request): # voterSupportingSave
"""
Save support for a single measure or candidate for one voter (voterSupportingSave)
Default to set this as a position for your friends only.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_supporting_save_for_api(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_bookmark_off_save_view(request):
"""
Un-mark the bookmark for a single measure, office or candidate for one voter (voterBookmarkOffSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_off_save_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_bookmark_on_save_view(request):
"""
Mark the bookmark for a single measure, office or candidate for one voter (voterBookmarkOnSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_on_save_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_bookmark_status_retrieve_view(request):
"""
Retrieve whether or not a bookmark is marked for an office, candidate or measure based on unique identifier
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_status_retrieve_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_all_bookmarks_status_retrieve_view(request): # voterAllBookmarksStatusRetrieve
"""
A list of all of the bookmarks that the voter has marked.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return voter_all_bookmarks_status_retrieve_for_api(
voter_device_id=voter_device_id)
def voter_twitter_save_to_current_account_view(request): # voterTwitterSaveToCurrentAccount
"""
Saving the results of signing in with Twitter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_twitter_save_to_current_account_for_api(voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def return_flag_value(request, variable_name, is_post=False):
try:
if is_post:
value = request.POST[variable_name]
else:
value = request.GET[variable_name]
value = value.strip()
value = convert_to_int(value)
except KeyError:
value = False
return value
def return_string_value_and_changed_boolean_from_get(request, variable_name):
value = request.GET.get(variable_name, False)
value_changed = False
if value is not False:
value = value.strip()
if value.lower() == 'false':
value = False
value_changed = False
else:
value_changed = True
return value, value_changed
@csrf_exempt
def voter_update_view(request): # voterUpdate
"""
Update profile-related information for this voter
:param request:
:return:
"""
from django.core.exceptions import RequestDataTooBig
status = ""
voter_updated = False
voter_name_needs_to_be_updated_in_activity = False
try:
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
except RequestDataTooBig:
status += "RequestDataTooBig"
json_data = {
'status': status,
'success': False,
'voter_device_id': False,
'facebook_email': False,
'facebook_profile_image_url_https': False,
'first_name': '',
'middle_name': '',
'last_name': '',
'twitter_profile_image_url_https': '',
'we_vote_hosted_profile_image_url_large': '',
'we_vote_hosted_profile_image_url_medium': '',
'we_vote_hosted_profile_image_url_tiny': '',
'voter_updated': False,
'interface_status_flags': 0,
'flag_integer_to_set': 0,
'flag_integer_to_unset': 0,
'notification_settings_flags': 0,
'notification_flag_integer_to_set': 0,
'notification_flag_integer_to_unset': 0,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
is_post = True if request.method == 'POST' else False
if is_post:
facebook_email_changed = positive_value_exists(request.POST.get('facebook_email_changed', False))
facebook_email = request.POST.get('facebook_email', '') if facebook_email_changed else False
facebook_profile_image_url_https_changed = \
positive_value_exists(request.POST.get('facebook_profile_image_url_https_changed', False))
facebook_profile_image_url_https = request.POST.get('facebook_profile_image_url_https', '') \
if facebook_profile_image_url_https_changed else False
first_name_changed = positive_value_exists(request.POST.get('first_name_changed', False))
first_name = request.POST.get('first_name', '') if first_name_changed else False
middle_name_changed = positive_value_exists(request.POST.get('middle_name_changed', False))
middle_name = request.POST.get('middle_name', '') if middle_name_changed else False
last_name_changed = positive_value_exists(request.POST.get('last_name_changed', False))
last_name = request.POST.get('last_name', '') if last_name_changed else False
full_name_changed = positive_value_exists(request.POST.get('full_name_changed', False))
full_name = request.POST.get('full_name', '') if full_name_changed else False
name_save_only_if_no_existing_names = request.POST.get('name_save_only_if_no_existing_names', False)
external_voter_id = request.POST.get('external_voter_id', False)
membership_organization_we_vote_id = request.POST.get('membership_organization_we_vote_id', False)
twitter_profile_image_url_https_changed = \
positive_value_exists(request.POST.get('twitter_profile_image_url_https_changed', False))
twitter_profile_image_url_https = request.POST.get('twitter_profile_image_url_https', '') \
if twitter_profile_image_url_https_changed else False
interface_status_flags = return_flag_value(request, 'interface_status_flags', is_post=True)
flag_integer_to_set = return_flag_value(request, 'flag_integer_to_set', is_post=True)
flag_integer_to_unset = return_flag_value(request, 'flag_integer_to_unset', is_post=True)
notification_settings_flags = return_flag_value(request, 'notification_settings_flags', is_post=True)
notification_flag_integer_to_set = return_flag_value(request, 'notification_flag_integer_to_set', is_post=True)
notification_flag_integer_to_unset = \
return_flag_value(request, 'notification_flag_integer_to_unset', is_post=True)
try:
send_journal_list = request.POST['send_journal_list']
except KeyError:
send_journal_list = False
voter_photo_from_file_reader = request.POST.get('voter_photo_from_file_reader', '')
voter_photo_changed = positive_value_exists(request.POST.get('voter_photo_changed', False))
profile_image_type_currently_active = request.POST.get('profile_image_type_currently_active', False)
profile_image_type_currently_active_changed = \
positive_value_exists(request.POST.get('profile_image_type_currently_active_changed', False))
else:
facebook_email, facebook_email_changed = \
return_string_value_and_changed_boolean_from_get(request, 'facebook_email')
facebook_profile_image_url_https, facebook_profile_image_url_https_changed = \
return_string_value_and_changed_boolean_from_get(request, 'facebook_profile_image_url_https')
first_name, first_name_changed = return_string_value_and_changed_boolean_from_get(request, 'first_name')
middle_name, middle_name_changed = return_string_value_and_changed_boolean_from_get(request, 'middle_name')
last_name, last_name_changed = return_string_value_and_changed_boolean_from_get(request, 'last_name')
full_name, full_name_changed = return_string_value_and_changed_boolean_from_get(request, 'full_name')
name_save_only_if_no_existing_names = request.GET.get('name_save_only_if_no_existing_names', False)
external_voter_id = request.GET.get('external_voter_id', False)
membership_organization_we_vote_id = request.GET.get('membership_organization_we_vote_id', False)
twitter_profile_image_url_https, twitter_profile_image_url_https_changed = \
return_string_value_and_changed_boolean_from_get(request, 'twitter_profile_image_url_https')
interface_status_flags = return_flag_value(request, 'interface_status_flags')
flag_integer_to_set = return_flag_value(request, 'flag_integer_to_set')
flag_integer_to_unset = return_flag_value(request, 'flag_integer_to_unset')
notification_settings_flags = return_flag_value(request, 'notification_settings_flags')
notification_flag_integer_to_set = return_flag_value(request, 'notification_flag_integer_to_set')
notification_flag_integer_to_unset = return_flag_value(request, 'notification_flag_integer_to_unset')
try:
send_journal_list = request.GET['send_journal_list']
except KeyError:
send_journal_list = False
voter_photo_from_file_reader = ''
voter_photo_changed = False
profile_image_type_currently_active = False
profile_image_type_currently_active_changed = False
# Voter has visited a private-labeled We Vote site, and we want to store that voter's id from another database
if external_voter_id is not False:
external_voter_id = external_voter_id.strip()
if external_voter_id.lower() == 'false':
external_voter_id = False
# Voter has visited a private-labeled We Vote site, and we want to connect this voter to that organization
if membership_organization_we_vote_id is not False:
membership_organization_we_vote_id = membership_organization_we_vote_id.strip()
if membership_organization_we_vote_id.lower() == 'false':
membership_organization_we_vote_id = False
device_id_results = is_voter_device_id_valid(voter_device_id)
if not device_id_results['success']:
status += "VOTER_DEVICE_ID_NOT_BALLOT " + device_id_results['status']
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': "",
'we_vote_hosted_profile_image_url_medium': "",
'we_vote_hosted_profile_image_url_tiny': "",
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
at_least_one_variable_has_changed = True if \
facebook_email \
or facebook_profile_image_url_https \
or first_name is not False \
or middle_name is not False \
or last_name is not False \
or full_name \
or interface_status_flags is not False \
or flag_integer_to_unset is not False \
or flag_integer_to_set is not False \
or notification_settings_flags is not False \
or notification_flag_integer_to_unset is not False \
or notification_flag_integer_to_set is not False \
or voter_photo_changed is not False \
or profile_image_type_currently_active_changed is not False \
or send_journal_list \
else False
external_voter_id_to_be_saved = True \
if (membership_organization_we_vote_id is not False and external_voter_id is not False) \
else False
voter_manager = VoterManager()
voter_results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
voter_id = voter_results['voter_id']
if not positive_value_exists(voter_id):
status += "VOTER_NOT_FOUND_FROM_DEVICE_ID-VOTER_UPDATE "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': "",
'we_vote_hosted_profile_image_url_medium': "",
'we_vote_hosted_profile_image_url_tiny': "",
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
# At this point, we have a valid voter
voter = voter_results['voter']
voter_we_vote_id = voter.we_vote_id
voter_full_name_at_start = voter.get_full_name(real_name_only=True)
if at_least_one_variable_has_changed or external_voter_id_to_be_saved:
pass
else:
# If here, we want to return the latest data from the voter object
status += "MISSING_VARIABLE-NO_VARIABLES_PASSED_IN_TO_CHANGE "
json_data = {
'status': status,
'success': True,
'voter_device_id': voter_device_id,
'facebook_email': voter.facebook_email,
'facebook_profile_image_url_https': voter.facebook_profile_image_url_https,
'first_name': voter.first_name,
'middle_name': voter.middle_name,
'last_name': voter.last_name,
'twitter_profile_image_url_https': voter.twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': voter.we_vote_hosted_profile_image_url_large,
'we_vote_hosted_profile_image_url_medium': voter.we_vote_hosted_profile_image_url_medium,
'we_vote_hosted_profile_image_url_tiny': voter.we_vote_hosted_profile_image_url_tiny,
'voter_updated': voter_updated,
'interface_status_flags': voter.interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': voter.notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
# These variables will contain copy of default profile photo
we_vote_hosted_profile_image_url_large = False
we_vote_hosted_profile_image_url_medium = False
we_vote_hosted_profile_image_url_tiny = False
we_vote_hosted_profile_twitter_image_url_large = False
we_vote_hosted_profile_twitter_image_url_medium = False
we_vote_hosted_profile_twitter_image_url_tiny = False
if twitter_profile_image_url_https:
# Cache original and resized images
# TODO: Replace voter.twitter_id with value from twitter link to voter
cache_results = cache_master_and_resized_image(
voter_we_vote_id=voter.we_vote_id,
twitter_id=voter.twitter_id,
twitter_screen_name=voter.twitter_screen_name,
twitter_profile_image_url_https=twitter_profile_image_url_https,
image_source=TWITTER)
cached_twitter_profile_image_url_https = cache_results['cached_twitter_profile_image_url_https']
we_vote_hosted_profile_twitter_image_url_large = cache_results['we_vote_hosted_profile_image_url_large']
we_vote_hosted_profile_twitter_image_url_medium = cache_results['we_vote_hosted_profile_image_url_medium']
we_vote_hosted_profile_twitter_image_url_tiny = cache_results['we_vote_hosted_profile_image_url_tiny']
if positive_value_exists(cached_twitter_profile_image_url_https):
twitter_profile_image_url_https = cached_twitter_profile_image_url_https
we_vote_hosted_profile_facebook_image_url_large = False
we_vote_hosted_profile_facebook_image_url_medium = False
we_vote_hosted_profile_facebook_image_url_tiny = False
if facebook_profile_image_url_https:
# Cache original and resized images
# TODO: Replace voter.facebook_id with value from facebook link to voter
cache_results = cache_master_and_resized_image(
voter_we_vote_id=voter.we_vote_id,
facebook_user_id=voter.facebook_id,
facebook_profile_image_url_https=facebook_profile_image_url_https,
image_source=FACEBOOK)
cached_facebook_profile_image_url_https = cache_results['cached_facebook_profile_image_url_https']
we_vote_hosted_profile_facebook_image_url_large = cache_results['we_vote_hosted_profile_image_url_large']
we_vote_hosted_profile_facebook_image_url_medium = cache_results['we_vote_hosted_profile_image_url_medium']
we_vote_hosted_profile_facebook_image_url_tiny = cache_results['we_vote_hosted_profile_image_url_tiny']
if positive_value_exists(cached_facebook_profile_image_url_https):
facebook_profile_image_url_https = cached_facebook_profile_image_url_https
#
# Save voter_photo_from_file_reader and get back we_vote_hosted_voter_photo_original_url
we_vote_hosted_profile_uploaded_image_url_large = False
we_vote_hosted_profile_uploaded_image_url_medium = False
we_vote_hosted_profile_uploaded_image_url_tiny = False
if voter_photo_changed and voter_photo_from_file_reader:
photo_results = voter_save_photo_from_file_reader(
voter_we_vote_id=voter_we_vote_id,
voter_photo_from_file_reader=voter_photo_from_file_reader)
if photo_results['we_vote_hosted_voter_photo_original_url']:
we_vote_hosted_voter_photo_original_url = photo_results['we_vote_hosted_voter_photo_original_url']
# Now we want to resize to a large version
create_resized_image_results = create_resized_images(
voter_we_vote_id=voter_we_vote_id,
voter_uploaded_profile_image_url_https=we_vote_hosted_voter_photo_original_url)
we_vote_hosted_profile_uploaded_image_url_large = \
create_resized_image_results['cached_resized_image_url_large']
we_vote_hosted_profile_uploaded_image_url_medium = \
create_resized_image_results['cached_resized_image_url_medium']
we_vote_hosted_profile_uploaded_image_url_tiny = \
create_resized_image_results['cached_resized_image_url_tiny']
elif voter_photo_changed:
# If here we are deleting an existing photo
we_vote_hosted_profile_uploaded_image_url_large = ''
we_vote_hosted_profile_uploaded_image_url_medium = ''
we_vote_hosted_profile_uploaded_image_url_tiny = ''
we_vote_hosted_profile_image_url_large = ''
we_vote_hosted_profile_image_url_medium = ''
we_vote_hosted_profile_image_url_tiny = ''
voter.profile_image_type_currently_active = PROFILE_IMAGE_TYPE_UNKNOWN
# We need profile_image_type_currently_active setting
if profile_image_type_currently_active_changed:
# In this case it is coming in from API call and does not need to be calculated
pass
else:
profile_image_type_currently_active = voter.profile_image_type_currently_active
if profile_image_type_currently_active not in \
[PROFILE_IMAGE_TYPE_FACEBOOK, PROFILE_IMAGE_TYPE_TWITTER, PROFILE_IMAGE_TYPE_UPLOADED]:
# Do we need to calculate a value to store?
continue_analyzing_profile_image_type_currently_active = True
if voter_photo_changed:
if we_vote_hosted_profile_uploaded_image_url_large and \
we_vote_hosted_profile_uploaded_image_url_large != '':
profile_image_type_currently_active_changed = True
profile_image_type_currently_active = PROFILE_IMAGE_TYPE_UPLOADED
we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_uploaded_image_url_large
we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_uploaded_image_url_medium
we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_uploaded_image_url_tiny
continue_analyzing_profile_image_type_currently_active = False
if continue_analyzing_profile_image_type_currently_active:
if we_vote_hosted_profile_facebook_image_url_large:
profile_image_type_currently_active_changed = True
profile_image_type_currently_active = PROFILE_IMAGE_TYPE_FACEBOOK
we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_facebook_image_url_large
we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_facebook_image_url_medium
we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_facebook_image_url_tiny
continue_analyzing_profile_image_type_currently_active = False
if continue_analyzing_profile_image_type_currently_active:
if we_vote_hosted_profile_twitter_image_url_large:
profile_image_type_currently_active_changed = True
profile_image_type_currently_active = PROFILE_IMAGE_TYPE_TWITTER
we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_twitter_image_url_large
we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_twitter_image_url_medium
we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_twitter_image_url_tiny
continue_analyzing_profile_image_type_currently_active = False
at_least_one_variable_has_changed = True if \
at_least_one_variable_has_changed \
or profile_image_type_currently_active_changed \
else False
if positive_value_exists(voter.first_name) or positive_value_exists(voter.last_name):
saved_first_or_last_name_exists = True
else:
saved_first_or_last_name_exists = False
incoming_first_or_last_name = positive_value_exists(first_name) or positive_value_exists(last_name)
# If a first_name or last_name is coming in, we want to ignore the full_name
if positive_value_exists(full_name) and not positive_value_exists(incoming_first_or_last_name):
incoming_full_name_can_be_processed = True
else:
incoming_full_name_can_be_processed = False
if incoming_full_name_can_be_processed:
# If here we want to parse full_name into first and last
first_name = extract_first_name_from_full_name(full_name)
last_name = extract_last_name_from_full_name(full_name)
if name_save_only_if_no_existing_names:
if saved_first_or_last_name_exists:
first_name = False
last_name = False
success = True
voter_manager = VoterManager()
voter_updated = False
linked_organization_we_vote_id = ''
if at_least_one_variable_has_changed:
results = voter_manager.update_voter_by_id(
voter_id,
facebook_email=facebook_email,
facebook_profile_image_url_https=facebook_profile_image_url_https,
first_name=first_name,
middle_name=middle_name,
last_name=last_name,
interface_status_flags=interface_status_flags,
flag_integer_to_set=flag_integer_to_set,
flag_integer_to_unset=flag_integer_to_unset,
notification_settings_flags=notification_settings_flags,
notification_flag_integer_to_set=notification_flag_integer_to_set,
notification_flag_integer_to_unset=notification_flag_integer_to_unset,
profile_image_type_currently_active=profile_image_type_currently_active,
twitter_profile_image_url_https=twitter_profile_image_url_https,
we_vote_hosted_profile_facebook_image_url_large=we_vote_hosted_profile_facebook_image_url_large,
we_vote_hosted_profile_facebook_image_url_medium=we_vote_hosted_profile_facebook_image_url_medium,
we_vote_hosted_profile_facebook_image_url_tiny=we_vote_hosted_profile_facebook_image_url_tiny,
we_vote_hosted_profile_image_url_large=we_vote_hosted_profile_image_url_large,
we_vote_hosted_profile_image_url_medium=we_vote_hosted_profile_image_url_medium,
we_vote_hosted_profile_image_url_tiny=we_vote_hosted_profile_image_url_tiny,
we_vote_hosted_profile_twitter_image_url_large=we_vote_hosted_profile_twitter_image_url_large,
we_vote_hosted_profile_twitter_image_url_medium=we_vote_hosted_profile_twitter_image_url_medium,
we_vote_hosted_profile_twitter_image_url_tiny=we_vote_hosted_profile_twitter_image_url_tiny,
we_vote_hosted_profile_uploaded_image_url_large=we_vote_hosted_profile_uploaded_image_url_large,
we_vote_hosted_profile_uploaded_image_url_medium=we_vote_hosted_profile_uploaded_image_url_medium,
we_vote_hosted_profile_uploaded_image_url_tiny=we_vote_hosted_profile_uploaded_image_url_tiny,
)
status += results['status']
success = results['success']
voter = results['voter']
voter_updated = results['voter_updated']
first_name = voter.first_name
last_name = voter.last_name
linked_organization_we_vote_id = voter.linked_organization_we_vote_id
organization_manager = OrganizationManager()
if external_voter_id_to_be_saved:
results = organization_manager.update_or_create_organization_membership_link_to_voter(
membership_organization_we_vote_id, external_voter_id, voter_we_vote_id)
status += results['status']
success = results['success']
# When the first or last name is changed, we want to update the organization name if the organization name
# starts with "Voter-" or organization.most_recent_name_update_from_first_and_last is True
voter_full_name = voter.get_full_name(real_name_only=True)
if positive_value_exists(voter_full_name):
if voter_full_name != voter_full_name_at_start:
voter_name_needs_to_be_updated_in_activity = True
voter_name_changed = False
if positive_value_exists(voter_full_name) \
and (incoming_first_or_last_name or incoming_full_name_can_be_processed) \
and positive_value_exists(linked_organization_we_vote_id):
voter_name_changed = True
if voter_name_changed or voter_photo_changed:
results = organization_manager.retrieve_organization_from_we_vote_id(linked_organization_we_vote_id)
if results['organization_found']:
organization = results['organization']
organization_changed = False
organization_name_changed = False
not_real_name = False
if positive_value_exists(organization.organization_name):
not_real_name = organization.organization_name.startswith('Voter-')
if positive_value_exists(organization.most_recent_name_update_from_voter_first_and_last) or not_real_name:
if not organization.most_recent_name_update_from_voter_first_and_last:
organization.most_recent_name_update_from_voter_first_and_last = True
organization_changed = True
if positive_value_exists(voter_full_name):
organization.organization_name = voter_full_name
organization_changed = True
organization_name_changed = True
if we_vote_hosted_profile_image_url_large is not False:
organization.we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_image_url_large
organization_changed = True
if we_vote_hosted_profile_image_url_medium is not False:
organization.we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_image_url_medium
organization_changed = True
if we_vote_hosted_profile_image_url_tiny is not False:
organization.we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_image_url_tiny
organization_changed = True
if organization_changed:
try:
organization.save()
if positive_value_exists(organization_name_changed):
from voter_guide.models import VoterGuideManager
voter_guide_manager = VoterGuideManager()
results = \
voter_guide_manager.update_organization_voter_guides_with_organization_data(organization)
status += results['status']
from organization.controllers import update_position_entered_details_from_organization
# TODO This can be made much more efficient
position_results = update_position_entered_details_from_organization(organization)
status += position_results['status']
if positive_value_exists(organization_name_changed) and not not_real_name or \
organization.we_vote_hosted_profile_image_url_tiny is not False:
from campaign.models import CampaignXManager
campaignx_manager = CampaignXManager()
owner_results = campaignx_manager.update_campaignx_owners_with_organization_change(
organization_we_vote_id=organization.we_vote_id,
organization_name=organization.organization_name,
we_vote_hosted_profile_image_url_tiny=organization.we_vote_hosted_profile_image_url_tiny,
)
status += owner_results['status']
supporter_results = campaignx_manager.update_campaignx_supporters_with_organization_change(
organization_we_vote_id=organization.we_vote_id,
supporter_name=organization.organization_name,
we_vote_hosted_profile_image_url_tiny=organization.we_vote_hosted_profile_image_url_tiny,
)
status += supporter_results['status']
except Exception as e:
status += "COULD_NOT_SAVE_ORGANIZATION: " + str(e) + " "
pass
if voter_name_needs_to_be_updated_in_activity:
from activity.models import ActivityManager
activity_manager = ActivityManager()
results = activity_manager.update_speaker_name_in_bulk(
speaker_voter_we_vote_id=voter_we_vote_id,
speaker_name=voter_full_name)
status += results['status']
json_data = {
'status': status,
'success': success,
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': we_vote_hosted_profile_image_url_large,
'we_vote_hosted_profile_image_url_medium': we_vote_hosted_profile_image_url_medium,
'we_vote_hosted_profile_image_url_tiny': we_vote_hosted_profile_image_url_tiny,
'voter_updated': voter_updated,
'interface_status_flags': voter.interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': voter.notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
def voter_notification_settings_update_view(request): # voterNotificationSettingsUpdate
"""
Update notification settings for voter based on secret key
:param request:
:return:
"""
status = ""
voter_found = False
voter_updated = False
normalized_email_address = ''
normalized_sms_phone_number = ''
# If we have an incoming GET value for a variable, use it. If we don't pass "False" into voter_update_for_api
# as a signal to not change the variable. (To set variables to False, pass in the string "False".)
try:
email_subscription_secret_key = request.GET['email_subscription_secret_key']
email_subscription_secret_key = email_subscription_secret_key.strip()
except KeyError:
email_subscription_secret_key = False
try:
sms_subscription_secret_key = request.GET['sms_subscription_secret_key']
sms_subscription_secret_key = sms_subscription_secret_key.strip()
except KeyError:
sms_subscription_secret_key = False
try:
interface_status_flags = request.GET['interface_status_flags']
interface_status_flags = interface_status_flags.strip()
interface_status_flags = convert_to_int(interface_status_flags)
except KeyError:
interface_status_flags = False
try:
flag_integer_to_set = request.GET['flag_integer_to_set']
flag_integer_to_set = flag_integer_to_set.strip()
flag_integer_to_set = convert_to_int(flag_integer_to_set)
except KeyError:
flag_integer_to_set = False
try:
flag_integer_to_unset = request.GET['flag_integer_to_unset']
flag_integer_to_unset = flag_integer_to_unset.strip()
flag_integer_to_unset = convert_to_int(flag_integer_to_unset)
except KeyError:
flag_integer_to_unset = False
try:
notification_settings_flags = request.GET['notification_settings_flags']
notification_settings_flags = notification_settings_flags.strip()
notification_settings_flags = convert_to_int(notification_settings_flags)
except KeyError:
notification_settings_flags = False
try:
notification_flag_integer_to_set = request.GET['notification_flag_integer_to_set']
notification_flag_integer_to_set = notification_flag_integer_to_set.strip()
notification_flag_integer_to_set = convert_to_int(notification_flag_integer_to_set)
if not positive_value_exists(notification_flag_integer_to_set):
notification_flag_integer_to_set = False
except KeyError:
notification_flag_integer_to_set = False
try:
notification_flag_integer_to_unset = request.GET['notification_flag_integer_to_unset']
notification_flag_integer_to_unset = notification_flag_integer_to_unset.strip()
notification_flag_integer_to_unset = convert_to_int(notification_flag_integer_to_unset)
if not positive_value_exists(notification_flag_integer_to_unset):
notification_flag_integer_to_unset = False
except KeyError:
notification_flag_integer_to_unset = False
at_least_one_variable_has_changed = True if \
interface_status_flags is not False \
or flag_integer_to_unset is not False \
or flag_integer_to_set is not False \
or notification_settings_flags is not False \
or notification_flag_integer_to_unset is not False \
or notification_flag_integer_to_set is not False \
else False
email_manager = EmailManager()
voter_manager = VoterManager()
voter_id = 0
voter_interface_status_flags = 0
voter_notification_settings_flags = 0
email_address_object_found = False
if positive_value_exists(email_subscription_secret_key):
email_results = email_manager.retrieve_email_address_object_from_secret_key(
subscription_secret_key=email_subscription_secret_key)
if email_results['email_address_object_found']:
status += "VOTER_NOTIFICATION_SETTINGS_UPDATE-EMAIL_ADDRESS_FOUND "
email_address_object = email_results['email_address_object']
email_address_object_found = True
normalized_email_address = email_address_object.normalized_email_address
voter_results = voter_manager.retrieve_voter_by_we_vote_id(email_address_object.voter_we_vote_id)
voter = voter_results['voter']
voter_found = True
voter_id = voter_results['voter_id']
voter_interface_status_flags = voter.interface_status_flags
voter_notification_settings_flags = voter.notification_settings_flags
else:
status += "EMAIL_ADDRESS_NOT_FOUND "
elif positive_value_exists(sms_subscription_secret_key):
# TODO Finish this
pass
else:
status += "SECRET_KEY_NOT_PROVIDED-VOTER_NOTIFICATION_SETTINGS_UPDATE "
json_data = {
'status': status,
'success': True,
'email_found': email_address_object_found,
'voter_found': voter_found,
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'normalized_email_address': normalized_email_address,
'normalized_sms_phone_number': normalized_sms_phone_number,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
if not positive_value_exists(voter_id):
if email_address_object_found:
status += "VOTER_NOT_FOUND_BUT_EMAIL_FOUND_FROM_SECRET_KEY "
else:
status += "VOTER_NOT_FOUND_FROM_SECRET_KEY "
voter_found = False
json_data = {
'status': status,
'success': True,
'email_found': email_address_object_found,
'voter_found': voter_found,
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'normalized_email_address': normalized_email_address,
'normalized_sms_phone_number': normalized_sms_phone_number,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
# At this point, we have a valid voter
if at_least_one_variable_has_changed:
pass
else:
# If here, there is nothing to change and we just want to return the latest data from the voter object
status += "MISSING_VARIABLE-NO_VARIABLES_PASSED_IN_TO_CHANGE "
json_data = {
'status': status,
'success': True,
'email_found': email_address_object_found,
'voter_found': voter_found,
'voter_updated': voter_updated,
'interface_status_flags': voter_interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'normalized_email_address': normalized_email_address,
'normalized_sms_phone_number': normalized_sms_phone_number,
'notification_settings_flags': voter_notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
success = True
voter_manager = VoterManager()
voter_updated = False
if at_least_one_variable_has_changed:
results = voter_manager.update_voter_by_id(
voter_id,
interface_status_flags=interface_status_flags,
flag_integer_to_set=flag_integer_to_set,
flag_integer_to_unset=flag_integer_to_unset,
notification_settings_flags=notification_settings_flags,
notification_flag_integer_to_set=notification_flag_integer_to_set,
notification_flag_integer_to_unset=notification_flag_integer_to_unset)
status += results['status']
success = results['success']
voter = results['voter']
voter_found = True
voter_updated = results['voter_updated']
voter_interface_status_flags = voter.interface_status_flags
voter_notification_settings_flags = voter.notification_settings_flags
json_data = {
'status': status,
'success': success,
'email_found': email_address_object_found,
'voter_found': voter_found,
'voter_updated': voter_updated,
'interface_status_flags': voter_interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'normalized_email_address': normalized_email_address,
'normalized_sms_phone_number': normalized_sms_phone_number,
'notification_settings_flags': voter_notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
def voter_verify_secret_code_view(request): # voterVerifySecretCode
"""
Compare a time-limited 6 digit secret code against this specific voter_device_id. If correct, sign in the
voter_device_id.
:param request:
:return:
"""
status = ''
success = True
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
secret_code = request.GET.get('secret_code', None)
code_sent_to_sms_phone_number = request.GET.get('code_sent_to_sms_phone_number', None)
voter_device_link_manager = VoterDeviceLinkManager()
voter_manager = VoterManager()
results = voter_device_link_manager.voter_verify_secret_code(
voter_device_id=voter_device_id, secret_code=secret_code)
incorrect_secret_code_entered = results['incorrect_secret_code_entered']
secret_code_verified = results['secret_code_verified']
number_of_tries_remaining_for_this_code = results['number_of_tries_remaining_for_this_code']
secret_code_system_locked_for_this_voter_device_id = results['secret_code_system_locked_for_this_voter_device_id']
voter_must_request_new_code = results['voter_must_request_new_code']
if not positive_value_exists(secret_code_verified):
status += results['status']
voter_found = False
voter = None
voter_device_link = None
if positive_value_exists(secret_code_verified):
status, voter, voter_found, voter_device_link = views_voter_utils.get_voter_from_request(request, status)
if not voter_found:
secret_code_verified = False
voter_must_request_new_code = True
if voter_found:
email_manager = EmailManager()
sms_manager = SMSManager()
if positive_value_exists(code_sent_to_sms_phone_number):
existing_verified_sms_found = False
new_owner_voter = None
# Check to see if this sms is already owned by an existing account
# We get the new sms being verified, so we can find the normalized_sms_phone_number and check to see
# if that is in use by someone else.
secret_key_results = sms_manager.retrieve_sms_phone_number_from_secret_key(
voter_device_link.sms_secret_key)
if secret_key_results['sms_phone_number_found']:
sms_from_secret_key = secret_key_results['sms_phone_number']
matching_results = sms_manager.retrieve_sms_phone_number(
sms_from_secret_key.normalized_sms_phone_number)
if matching_results['sms_phone_number_found']:
sms_phone_number_from_normalized = matching_results['sms_phone_number']
if positive_value_exists(sms_phone_number_from_normalized.sms_ownership_is_verified):
if positive_value_exists(sms_phone_number_from_normalized.voter_we_vote_id):
voter_results = voter_manager.retrieve_voter_by_we_vote_id(
sms_phone_number_from_normalized.voter_we_vote_id)
if voter_results['voter_found']:
voter_from_normalized = voter_results['voter']
# If here we know the voter account still exists
if voter_from_normalized.we_vote_id != voter.we_vote_id:
existing_verified_sms_found = True
new_owner_voter = voter_from_normalized
elif matching_results['sms_phone_number_list_found']:
sms_phone_number_list = matching_results['sms_phone_number_list']
for sms_phone_number_from_normalized in sms_phone_number_list:
if positive_value_exists(sms_phone_number_from_normalized.sms_ownership_is_verified):
if positive_value_exists(sms_phone_number_from_normalized.voter_we_vote_id):
voter_results = voter_manager.retrieve_voter_by_we_vote_id(
sms_phone_number_from_normalized.voter_we_vote_id)
if voter_results['voter_found']:
voter_from_normalized = voter_results['voter']
# If here we know the voter account still exists
if voter_from_normalized.we_vote_id != voter.we_vote_id:
existing_verified_sms_found = True
new_owner_voter = voter_from_normalized
break
else:
pass
if existing_verified_sms_found:
# Merge existing account with new account
merge_results = voter_merge_two_accounts_action(
voter, new_owner_voter, voter_device_link, status=status)
status += merge_results['status']
success = merge_results['success']
else:
# Find and verify the unverified email we are verifying
sms_results = sms_manager.verify_sms_phone_number_from_secret_key(
voter_device_link.sms_secret_key)
if sms_results['sms_phone_number_found']:
sms_phone_number = sms_results['sms_phone_number']
status += "SMS_FOUND_FROM_VERIFY "
try:
# Attach the sms_phone_number to the current voter
voter_manager.update_voter_sms_ownership_verified(
voter, sms_phone_number)
except Exception as e:
status += "UNABLE_TO_CONNECT_VERIFIED_SMS_WITH_THIS_ACCOUNT " + str(e) + " "
else:
status += sms_results['status']
if positive_value_exists(voter_device_link.sms_secret_key):
# We remove secret_key's to avoid future collisions in the voter_device_link
clear_results = sms_manager.clear_secret_key_from_sms_phone_number(voter_device_link.sms_secret_key)
status += clear_results['status']
clear_results = voter_device_link_manager.clear_secret_key(
sms_secret_key=voter_device_link.sms_secret_key)
status += clear_results['status']
else:
# Default to code being sent to an email address
existing_verified_email_address_found = False
new_owner_voter = None
email_manager = EmailManager()
# Check to see if this email_address is already owned by an existing account
# We get the new email being verified, so we can find the normalized_email_address and check to see
# if that is in use by someone else.
secret_key_results = email_manager.retrieve_email_address_object_from_secret_key(
voter_device_link.email_secret_key)
if secret_key_results['email_address_object_found']:
email_object_from_secret_key = secret_key_results['email_address_object']
matching_results = email_manager.retrieve_email_address_object(
email_object_from_secret_key.normalized_email_address)
if matching_results['email_address_object_found']:
email_address_from_normalized = matching_results['email_address_object']
if positive_value_exists(email_address_from_normalized.email_ownership_is_verified):
if positive_value_exists(email_address_from_normalized.voter_we_vote_id):
voter_results = voter_manager.retrieve_voter_by_we_vote_id(
email_address_from_normalized.voter_we_vote_id)
if voter_results['voter_found']:
voter_from_normalized = voter_results['voter']
# If here we know the voter account still exists
if voter_from_normalized.we_vote_id != voter.we_vote_id:
existing_verified_email_address_found = True
new_owner_voter = voter_from_normalized
elif matching_results['email_address_list_found']:
email_address_list = matching_results['email_address_list']
for email_address_from_normalized in email_address_list:
if positive_value_exists(email_address_from_normalized.email_ownership_is_verified):
if positive_value_exists(email_address_from_normalized.voter_we_vote_id):
voter_results = voter_manager.retrieve_voter_by_we_vote_id(
email_address_from_normalized.voter_we_vote_id)
if voter_results['voter_found']:
voter_from_normalized = voter_results['voter']
# If here we know the voter account still exists
if voter_from_normalized.we_vote_id != voter.we_vote_id:
existing_verified_email_address_found = True
new_owner_voter = voter_from_normalized
break
else:
pass
if existing_verified_email_address_found:
# Merge existing account with new account
merge_results = voter_merge_two_accounts_action(
voter, new_owner_voter, voter_device_link, status=status)
status += merge_results['status']
success = merge_results['success']
else:
# Find and verify the unverified email we are verifying
email_results = email_manager.verify_email_address_object_from_secret_key(
voter_device_link.email_secret_key)
if email_results['email_address_object_found']:
email_address_object = email_results['email_address_object']
status += "EMAIL_ADDRESS_FOUND_FROM_VERIFY "
try:
# Attach the email_address_object to the current voter
voter_manager.update_voter_email_ownership_verified(
voter, email_address_object)
except Exception as e:
status += "UNABLE_TO_CONNECT_VERIFIED_EMAIL_WITH_THIS_ACCOUNT " + str(e) + " "
else:
status += email_results['status']
if positive_value_exists(voter_device_link.email_secret_key):
# We remove secret_key's to avoid future collisions in the voter_device_link
clear_results = email_manager.clear_secret_key_from_email_address(
voter_device_link.email_secret_key)
status += clear_results['status']
clear_results = voter_device_link_manager.clear_secret_key(
email_secret_key=voter_device_link.email_secret_key)
status += clear_results['status']
json_data = {
'status': status,
'success': success,
'incorrect_secret_code_entered': incorrect_secret_code_entered,
'number_of_tries_remaining_for_this_code': number_of_tries_remaining_for_this_code,
'secret_code_system_locked_for_this_voter_device_id': secret_code_system_locked_for_this_voter_device_id,
'secret_code_verified': secret_code_verified,
'voter_must_request_new_code': voter_must_request_new_code,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
@csrf_exempt
def voter_send_google_contacts_view(request): # voterSendGoogleContacts
"""
Receive the voter's google contacts that they allowed the download from the Campaign app
:param request:
:return:
"""
success = True
status = ''
status, voter, voter_found, voter_device_link = views_voter_utils.get_voter_from_request(request, status)
contacts_string = request.POST.get('contacts', None)
contacts = json.loads(contacts_string)
j = 0
if contacts is not None:
success = True
for contact in contacts:
j += 1
print(str(j) + " " + json.dumps(contact))
json_data = {
'status': status,
'success': success,
'we_vote_id_for_google_contacts': voter.we_vote_id,
'contacts_stored': len(contacts),
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_voter.py",
"copies": "1",
"size": "152099",
"license": "mit",
"hash": 1745390494599923000,
"line_mean": 51.5203729282,
"line_max": 120,
"alpha_frac": 0.6126667499,
"autogenerated": false,
"ratio": 3.7147148613994383,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48273816112994383,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from apis_v1.controllers import voter_count
from ballot.controllers import voter_ballot_items_retrieve_for_api
from ballot.models import copy_existing_ballot_items_from_stored_ballot
from config.base import get_environment_variable
from django.http import HttpResponse
from django_user_agents.utils import get_user_agent
from email_outbound.controllers import voter_email_address_save_for_api, voter_email_address_retrieve_for_api, \
voter_email_address_sign_in_for_api, voter_email_address_verify_for_api
from wevote_functions.functions import extract_first_name_from_full_name, extract_last_name_from_full_name
from follow.controllers import voter_issue_follow_for_api
from geoip.controllers import voter_location_retrieve_from_ip_for_api
from image.controllers import TWITTER, FACEBOOK, cache_master_and_resized_image
from import_export_ballotpedia.controllers import voter_ballot_items_retrieve_from_ballotpedia_for_api
from import_export_facebook.controllers import voter_facebook_sign_in_retrieve_for_api, \
voter_facebook_sign_in_save_for_api
from import_export_google_civic.controllers import voter_ballot_items_retrieve_from_google_civic_for_api
from import_export_twitter.controllers import voter_twitter_save_to_current_account_for_api
import json
from position.controllers import voter_all_positions_retrieve_for_api, \
voter_position_retrieve_for_api, voter_position_comment_save_for_api, voter_position_visibility_save_for_api
from position_like.controllers import voter_position_like_off_save_for_api, \
voter_position_like_on_save_for_api, voter_position_like_status_retrieve_for_api
from ballot.controllers import choose_election_and_prepare_ballot_data, voter_ballot_list_retrieve_for_api
from ballot.models import OFFICE, CANDIDATE, MEASURE, VoterBallotSavedManager
from bookmark.controllers import voter_all_bookmarks_status_retrieve_for_api, voter_bookmark_off_save_for_api, \
voter_bookmark_on_save_for_api, voter_bookmark_status_retrieve_for_api
from support_oppose_deciding.controllers import voter_opposing_save, voter_stop_opposing_save, \
voter_stop_supporting_save, voter_supporting_save_for_api
from voter.controllers import voter_address_retrieve_for_api, voter_create_for_api, voter_merge_two_accounts_for_api, \
voter_photo_save_for_api, voter_retrieve_for_api, voter_sign_out_for_api, \
voter_split_into_two_accounts_for_api
from voter.models import BALLOT_ADDRESS, VoterAddress, \
VoterAddressManager, VoterDeviceLink, VoterDeviceLinkManager, VoterManager
from voter_guide.controllers import voter_follow_all_organizations_followed_by_organization_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_maximum_number_to_retrieve_from_request, \
get_voter_device_id, is_voter_device_id_valid, positive_value_exists
from donate.controllers import donation_history_for_a_voter
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def voter_address_retrieve_view(request): # voterAddressRetrieve
"""
Retrieve an address for this voter so we can figure out which ballot to display
:param request:
:return:
"""
voter_address_manager = VoterAddressManager()
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
else:
voter_device_link = VoterDeviceLink()
voter_id = 0
guess_if_no_address_saved = request.GET.get('guess_if_no_address_saved', True)
if guess_if_no_address_saved == 'false':
guess_if_no_address_saved = False
elif guess_if_no_address_saved == 'False':
guess_if_no_address_saved = False
elif guess_if_no_address_saved == '0':
guess_if_no_address_saved = False
status = ''
voter_address_retrieve_results = voter_address_retrieve_for_api(voter_device_id)
if voter_address_retrieve_results['address_found']:
status += voter_address_retrieve_results['status']
if positive_value_exists(voter_address_retrieve_results['google_civic_election_id']):
google_civic_election_id = voter_address_retrieve_results['google_civic_election_id']
else:
# This block of code helps us if the google_civic_election_id hasn't been saved in the voter_address table
# We retrieve voter_device_link
google_civic_election_id = 0
# Retrieve the voter_address
voter_address_results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id,
voter_address)
status += results['status']
if results['voter_ballot_saved_found']:
google_civic_election_id = results['google_civic_election_id']
json_data = {
'voter_device_id': voter_address_retrieve_results['voter_device_id'],
'address_type': voter_address_retrieve_results['address_type'],
'text_for_map_search': voter_address_retrieve_results['text_for_map_search'],
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': voter_address_retrieve_results['ballot_location_display_name'],
'ballot_returned_we_vote_id': voter_address_retrieve_results['ballot_returned_we_vote_id'],
'voter_entered_address': voter_address_retrieve_results['voter_entered_address'],
'voter_specific_ballot_from_google_civic':
voter_address_retrieve_results['voter_specific_ballot_from_google_civic'],
'latitude': voter_address_retrieve_results['latitude'],
'longitude': voter_address_retrieve_results['longitude'],
'normalized_line1': voter_address_retrieve_results['normalized_line1'],
'normalized_line2': voter_address_retrieve_results['normalized_line2'],
'normalized_city': voter_address_retrieve_results['normalized_city'],
'normalized_state': voter_address_retrieve_results['normalized_state'],
'normalized_zip': voter_address_retrieve_results['normalized_zip'],
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
status += voter_address_retrieve_results['status'] + ", "
# If we are here, then an address wasn't found, and we either want to return that info, or take a guess
# at the voter's location by looking it up by IP address
if not positive_value_exists(guess_if_no_address_saved):
# Do not guess at an address
status += 'DO_NOT_GUESS_IF_NO_ADDRESS_SAVED'
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': 0,
'ballot_location_display_name': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'ballot_returned_we_vote_id': '',
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
status += 'GUESS_IF_NO_ADDRESS_SAVED' + ", "
# If here, we are going to guess at the voter's location based on IP address
voter_location_results = voter_location_retrieve_from_ip_for_api(request)
# # TODO DALE TEMP
# voter_location_results['voter_location_found'] = True
# voter_location_results['voter_location'] = "New York, NY"
# voter_location_results['status'] = "TODO DALE Temp setting of voter_location to New York"
if voter_location_results['voter_location_found']:
status += 'VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_FOUND_FROM_IP '
# Since a new location was found, we need to save the address and then reach out to Google Civic
text_for_map_search = voter_location_results['voter_location']
status += '*** ' + text_for_map_search + ' ***, '
google_civic_election_id = 0
voter_address_save_results = voter_address_manager.update_or_create_voter_address(
voter_id, BALLOT_ADDRESS, text_for_map_search)
status += voter_address_save_results['status'] + ", "
if voter_address_save_results['success'] and voter_address_save_results['voter_address_found']:
voter_address = voter_address_save_results['voter_address']
use_test_election = False
# Reach out to Google and populate ballot items in the database with fresh ballot data
# NOTE: 2016-05-26 Google civic NEVER returns a ballot for City, State ZIP, so we could change this
# DALE 2018-09-06 TURNED OFF
# google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api(
# voter_device_id, text_for_map_search, use_test_election)
# status += google_retrieve_results['status'] + ", "
#
# if positive_value_exists(google_retrieve_results['google_civic_election_id']):
# # Update voter_address with the google_civic_election_id retrieved from Google Civic
# # and clear out ballot_saved information
# google_civic_election_id = google_retrieve_results['google_civic_election_id']
#
# voter_address.google_civic_election_id = google_civic_election_id
# voter_address_update_results = voter_address_manager.update_existing_voter_address_object(
# voter_address)
#
# if voter_address_update_results['success']:
# # Replace the former google_civic_election_id from this voter_device_link
# voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
# voter_device_id)
# if voter_device_link_results['voter_device_link_found']:
# voter_device_link = voter_device_link_results['voter_device_link']
# voter_device_link_manager.update_voter_device_link_with_election_id(
# voter_device_link, google_retrieve_results['google_civic_election_id'])
#
# else:
# # This block of code helps us if the google_civic_election_id wasn't found when we reached out
# # to the Google Civic API, following finding the voter's location from IP address.
# google_civic_election_id = 0
# We retrieve voter_device_link
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
else:
voter_device_link = VoterDeviceLink()
# Retrieve the voter_address
voter_address_results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)
if voter_address_results['voter_address_found']:
voter_address = voter_address_results['voter_address']
else:
voter_address = VoterAddress()
results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id,
voter_address)
status += results['status']
if results['voter_ballot_saved_found']:
google_civic_election_id = results['google_civic_election_id']
voter_address_retrieve_results = voter_address_retrieve_for_api(voter_device_id)
status += voter_address_retrieve_results['status']
if voter_address_retrieve_results['address_found']:
json_data = {
'voter_device_id': voter_device_id,
'address_type': voter_address_retrieve_results['address_type'],
'text_for_map_search': voter_address_retrieve_results['text_for_map_search'],
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': voter_address_retrieve_results['ballot_location_display_name'],
'ballot_returned_we_vote_id': voter_address_retrieve_results['ballot_returned_we_vote_id'],
'voter_entered_address': voter_address_retrieve_results['voter_entered_address'],
'voter_specific_ballot_from_google_civic':
voter_address_retrieve_results['voter_specific_ballot_from_google_civic'],
'latitude': voter_address_retrieve_results['latitude'],
'longitude': voter_address_retrieve_results['longitude'],
'normalized_line1': voter_address_retrieve_results['normalized_line1'],
'normalized_line2': voter_address_retrieve_results['normalized_line2'],
'normalized_city': voter_address_retrieve_results['normalized_city'],
'normalized_state': voter_address_retrieve_results['normalized_state'],
'normalized_zip': voter_address_retrieve_results['normalized_zip'],
'success': voter_address_retrieve_results['success'],
'status': status,
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
else:
# Address not found from IP address
status += 'VOTER_ADDRESS_RETRIEVE_PART2_NO_ADDRESS'
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': google_civic_election_id,
'ballot_location_display_name': '',
'ballot_returned_we_vote_id': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': voter_address_retrieve_results['success'],
'status': voter_address_retrieve_results['status'],
'address_found': voter_address_retrieve_results['address_found'],
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
else:
status += 'VOTER_ADDRESS_RETRIEVE-VOTER_LOCATION_NOT_FOUND_FROM_IP: '
status += voter_location_results['status']
json_data = {
'voter_device_id': voter_device_id,
'address_type': '',
'text_for_map_search': '',
'google_civic_election_id': 0,
'ballot_location_display_name': '',
'ballot_returned_we_vote_id': '',
'voter_entered_address': False,
'voter_specific_ballot_from_google_civic': False,
'latitude': '',
'longitude': '',
'normalized_line1': '',
'normalized_line2': '',
'normalized_city': '',
'normalized_state': '',
'normalized_zip': '',
'success': False,
'status': status,
'address_found': False,
'guess_if_no_address_saved': guess_if_no_address_saved,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_address_save_view(request): # voterAddressSave
"""
Save or update an address for this voter. Once the address is saved, update the ballot information.
:param request:
:return:
"""
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
simple_save = positive_value_exists(request.GET.get('simple_save', False))
ballot_location_display_name = ''
ballot_returned_we_vote_id = ''
text_for_map_search_saved = ''
voter_entered_address = True
voter_specific_ballot_from_google_civic = False
status = ""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
try:
text_for_map_search = request.GET['text_for_map_search']
text_for_map_search = text_for_map_search.strip()
address_variable_exists = True
except KeyError:
text_for_map_search = ''
address_variable_exists = False
device_id_results = is_voter_device_id_valid(voter_device_id)
if not device_id_results['success']:
status += device_id_results['status']
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if not address_variable_exists:
status += "MISSING_GET_VARIABLE-ADDRESS"
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# We retrieve voter_device_link
voter_ballot_saved_manager = VoterBallotSavedManager()
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
else:
status += "VOTER_DEVICE_LINK_NOT_FOUND_FROM_DEVICE_ID"
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if not positive_value_exists(voter_id):
status += "VOTER_NOT_FOUND_FROM_DEVICE_ID-VOTER_ADDRESS_SAVE "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
# Save the address value, and clear out ballot_saved information
voter_address_manager = VoterAddressManager()
voter_address_save_results = voter_address_manager.update_or_create_voter_address(
voter_id, BALLOT_ADDRESS, text_for_map_search, google_civic_election_id, voter_entered_address)
# TODO DALE 2017-07-17 This needs a fresh look:
# , google_civic_election_id
# If simple_save is passed in only save address and then send response (you must pass in a google_civic_election_id)
if positive_value_exists(simple_save) and positive_value_exists(google_civic_election_id):
success = voter_address_save_results['success'] and voter_address_save_results['voter_address_found']
status += "SIMPLE_ADDRESS_SAVE"
json_data = {
'status': status,
'success': success,
'voter_device_id': voter_device_id,
'text_for_map_search': text_for_map_search,
'simple_save': simple_save,
'google_civic_election_id': google_civic_election_id
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
if voter_address_save_results['success'] and voter_address_save_results['voter_address_found']:
# # Remove the former google_civic_election_id from this voter_device_id
# voter_device_link_manager.update_voter_device_link_with_election_id(voter_device_link, 0)
voter_address = voter_address_save_results['voter_address']
use_test_election = False
turn_off_direct_voter_ballot_retrieve = False # Search for this variable elsewhere
default_election_data_source_is_ballotpedia = True
if turn_off_direct_voter_ballot_retrieve:
# We set this option when we want to force the retrieval of a nearby ballot
pass
elif default_election_data_source_is_ballotpedia:
status += "VOTER_ADDRESS_SAVE-SHOULD_WE_USE_BALLOTPEDIA_API? "
length_at_which_we_suspect_address_has_street = 25
length_of_text_for_map_search = 0
if isinstance(text_for_map_search, str):
length_of_text_for_map_search = len(text_for_map_search)
was_refreshed_from_ballotpedia_just_now = False
# We don't want to call Ballotpedia when we just have "City, State ZIP". Since we don't always know
# whether we have a street address or not, then we use a simple string length cut-off.
if length_of_text_for_map_search > length_at_which_we_suspect_address_has_street:
status += "TEXT_FOR_MAP_SEARCH_LONG_ENOUGH "
# 1a) Get ballot data from Ballotpedia for the actual VoterAddress
ballotpedia_retrieve_results = voter_ballot_items_retrieve_from_ballotpedia_for_api(
voter_device_id, text_for_map_search)
status += ballotpedia_retrieve_results['status']
if ballotpedia_retrieve_results['google_civic_election_id'] \
and ballotpedia_retrieve_results['contests_retrieved']:
was_refreshed_from_ballotpedia_just_now = True
is_from_substituted_address = False
substituted_address_nearby = ''
is_from_test_address = False
polling_location_we_vote_id_source = '' # Not used when retrieving directly for the voter
# We update the voter_address with this google_civic_election_id outside of this function
# Save the meta information for this ballot data
save_results = voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id,
ballotpedia_retrieve_results['google_civic_election_id'],
ballotpedia_retrieve_results['state_code'],
ballotpedia_retrieve_results['election_day_text'],
ballotpedia_retrieve_results['election_description_text'],
ballotpedia_retrieve_results['text_for_map_search'],
substituted_address_nearby,
is_from_substituted_address,
is_from_test_address,
polling_location_we_vote_id_source,
ballotpedia_retrieve_results['ballot_location_display_name'],
ballotpedia_retrieve_results['ballot_returned_we_vote_id'],
ballotpedia_retrieve_results['ballot_location_shortcut'],
original_text_city=ballotpedia_retrieve_results['original_text_city'],
original_text_state=ballotpedia_retrieve_results['original_text_state'],
original_text_zip=ballotpedia_retrieve_results['original_text_zip'],
)
status += save_results['status']
else:
status += "NOT_REACHING_OUT_TO_BALLOTPEDIA "
if not was_refreshed_from_ballotpedia_just_now:
# 2) Copy ballot data from a nearby address, previously retrieved and cached within We Vote
copy_results = copy_existing_ballot_items_from_stored_ballot(voter_id, text_for_map_search)
status += copy_results['status']
if copy_results['ballot_returned_copied']:
# If this ballot_returned entry is the result of searching based on an address, as opposed to
# a specific_ballot_requested, we want to update the VoterAddress
if positive_value_exists(voter_address.text_for_map_search):
try:
voter_address.ballot_location_display_name = copy_results['ballot_location_display_name']
voter_address.ballot_returned_we_vote_id = copy_results['ballot_returned_we_vote_id']
voter_address.save()
except Exception as e:
pass
# And now store the details of this ballot for this voter
is_from_substituted_address = True
is_from_test_address = False
save_results = voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id,
copy_results['google_civic_election_id'],
copy_results['state_code'],
copy_results['election_day_text'],
copy_results['election_description_text'],
text_for_map_search,
copy_results['substituted_address_nearby'],
is_from_substituted_address,
is_from_test_address,
copy_results['polling_location_we_vote_id_source'],
copy_results['ballot_location_display_name'],
copy_results['ballot_returned_we_vote_id'],
copy_results['ballot_location_shortcut'],
substituted_address_city=copy_results['original_text_city'],
substituted_address_state=copy_results['original_text_state'],
substituted_address_zip=copy_results['original_text_zip'],
)
status += save_results['status']
else:
# Reach out to Google and populate ballot items in the database with fresh ballot data
google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api( # DEBUG=1
voter_device_id, text_for_map_search, use_test_election)
# Update voter_address with the google_civic_election_id retrieved from Google Civic
# and clear out ballot_saved information IFF we got a valid google_civic_election_id back
if google_retrieve_results['google_civic_election_id']:
google_civic_election_id = convert_to_int(google_retrieve_results['google_civic_election_id'])
else:
# Leave google_civic_election_id as it was at the top of this function
pass
if google_retrieve_results['ballot_location_display_name']:
ballot_location_display_name = google_retrieve_results['ballot_location_display_name']
if google_retrieve_results['ballot_returned_we_vote_id']:
ballot_returned_we_vote_id = google_retrieve_results['ballot_returned_we_vote_id']
# At this point proceed to update google_civic_election_id whether it is a positive integer or zero
# First retrieve the latest address, since it gets saved when we retrieve from google civic
updated_address_results = voter_address_manager.retrieve_address(voter_address.id)
if updated_address_results['voter_address_found']:
voter_address = updated_address_results['voter_address']
voter_address.google_civic_election_id = google_civic_election_id
voter_address.ballot_location_display_name = ballot_location_display_name
voter_address.ballot_returned_we_vote_id = ballot_returned_we_vote_id
voter_entered_address = voter_address.voter_entered_address
voter_specific_ballot_from_google_civic = voter_address.refreshed_from_google
voter_address_update_results = voter_address_manager.update_existing_voter_address_object(voter_address)
if voter_address_update_results['success']:
# Replace the former google_civic_election_id from this voter_device_link
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_device_link_manager.update_voter_device_link_with_election_id(
voter_device_link, google_civic_election_id)
if voter_address_update_results['voter_address_found']:
voter_address = voter_address_update_results['voter_address']
text_for_map_search_saved = voter_address.text_for_map_search
json_data = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id,
ballot_returned_we_vote_id)
json_data['simple_save'] = simple_save
json_data['address'] = {
'text_for_map_search': text_for_map_search_saved,
'google_civic_election_id': google_civic_election_id,
'ballot_returned_we_vote_id': ballot_returned_we_vote_id,
'ballot_location_display_name': ballot_location_display_name,
'voter_entered_address': voter_entered_address,
'voter_specific_ballot_from_google_civic': voter_specific_ballot_from_google_civic,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_ballot_items_retrieve_view(request): # voterBallotItemsRetrieve
"""
Request the ballot data requested by the voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# If passed in, we want to look at
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
ballot_returned_we_vote_id = request.GET.get('ballot_returned_we_vote_id', '')
ballot_location_shortcut = request.GET.get('ballot_location_shortcut', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
if use_test_election:
google_civic_election_id = 2000 # The Google Civic test election
json_data = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id,
ballot_returned_we_vote_id, ballot_location_shortcut)
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_ballot_items_retrieve_from_google_civic_view(request): # voterBallotItemsRetrieveFromGoogleCivic
voter_device_id = get_voter_device_id(request)
text_for_map_search = request.GET.get('text_for_map_search', '')
use_test_election = positive_value_exists(request.GET.get('use_test_election', False))
voter_id = 0
original_text_city = ''
original_text_state = ''
original_text_zip = ''
google_retrieve_results = voter_ballot_items_retrieve_from_google_civic_for_api(
voter_device_id, text_for_map_search, use_test_election)
if google_retrieve_results['google_civic_election_id'] and not use_test_election:
# After the ballot is retrieved from google we want to save some info about it for the voter
if positive_value_exists(voter_device_id):
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
if voter_device_link_results['voter_device_link_found']:
voter_device_link = voter_device_link_results['voter_device_link']
voter_id = voter_device_link.voter_id
if positive_value_exists(google_retrieve_results['ballot_returned_we_vote_id']):
ballot_returned = google_retrieve_results['ballot_returned']
original_text_city = ballot_returned.normalized_city
original_text_state = ballot_returned.normalized_state
original_text_zip = ballot_returned.normalized_zip
if positive_value_exists(voter_id):
voter_ballot_saved_manager = VoterBallotSavedManager()
is_from_substituted_address = False
substituted_address_nearby = ''
is_from_test_address = False
polling_location_we_vote_id_source = "" # Not used when retrieving directly from Google Civic
# We don't update the voter_address because this view might be used independent of the voter_address
# Save the meta information for this ballot data. If it fails, ignore the failure
voter_ballot_saved_manager.update_or_create_voter_ballot_saved(
voter_id,
google_retrieve_results['google_civic_election_id'],
google_retrieve_results['state_code'],
google_retrieve_results['election_day_text'],
google_retrieve_results['election_description_text'],
google_retrieve_results['text_for_map_search'],
substituted_address_nearby,
is_from_substituted_address,
is_from_test_address,
polling_location_we_vote_id_source,
google_retrieve_results['ballot_location_display_name'],
google_retrieve_results['ballot_returned_we_vote_id'],
google_retrieve_results['ballot_location_shortcut'],
original_text_city=original_text_city,
original_text_state=original_text_state,
original_text_zip=original_text_zip,
)
return HttpResponse(json.dumps(google_retrieve_results), content_type='application/json')
def voter_ballot_list_retrieve_view(request): # voterBallotListRetrieve
"""
(voterBallotListRetrieve) Retrieve a list of election ballots per voter_id.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter_id = 0
if positive_value_exists(voter_device_id):
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id,
read_only=True)
voter_device_link = voter_device_link_results['voter_device_link']
if voter_device_link_results['voter_device_link_found']:
voter_id = voter_device_link.voter_id
if not positive_value_exists(voter_id):
json_data = {
'status': "VOTER_ID_MISSING",
'success': False,
'voter_device_id': voter_device_id,
'voter_ballot_list_found': False,
'voter_ballot_list': [],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_ballot_list_retrieve_for_api(voter_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'voter_ballot_list_found': results['voter_ballot_list_found'],
'voter_ballot_list': results['voter_ballot_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_count_view(request): # voterCount
return voter_count()
def voter_create_view(request): # voterCreate
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return voter_create_for_api(voter_device_id)
def voter_email_address_retrieve_view(request): # voterEmailAddressRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_email_address_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_address_list_found': results['email_address_list_found'],
'email_address_list': results['email_address_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_save_view(request): # voterEmailAddressSave
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
text_for_email_address = request.GET.get('text_for_email_address', '')
incoming_email_we_vote_id = request.GET.get('email_we_vote_id', '')
resend_verification_email = positive_value_exists(request.GET.get('resend_verification_email', False))
send_link_to_sign_in = positive_value_exists(request.GET.get('send_link_to_sign_in', False))
make_primary_email = positive_value_exists(request.GET.get('make_primary_email', False))
delete_email = positive_value_exists(request.GET.get('delete_email', ""))
is_cordova = positive_value_exists(request.GET.get('is_cordova', False))
results = voter_email_address_save_for_api(voter_device_id=voter_device_id,
text_for_email_address=text_for_email_address,
incoming_email_we_vote_id=incoming_email_we_vote_id,
send_link_to_sign_in=send_link_to_sign_in,
resend_verification_email=resend_verification_email,
make_primary_email=make_primary_email,
delete_email=delete_email,
is_cordova=is_cordova,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'text_for_email_address': text_for_email_address,
'make_primary_email': make_primary_email,
'delete_email': delete_email,
'email_address_we_vote_id': results['email_address_we_vote_id'],
'email_address_saved_we_vote_id': results['email_address_saved_we_vote_id'],
'email_address_already_owned_by_other_voter': results['email_address_already_owned_by_other_voter'],
'email_address_created': results['email_address_created'],
'email_address_deleted': results['email_address_deleted'],
'verification_email_sent': results['verification_email_sent'],
'link_to_sign_in_email_sent': results['link_to_sign_in_email_sent'],
'email_address_found': results['email_address_found'],
'email_address_list_found': results['email_address_list_found'],
'email_address_list': results['email_address_list'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_sign_in_view(request): # voterEmailAddressSignIn
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
yes_please_merge_accounts = request.GET.get('yes_please_merge_accounts', '')
yes_please_merge_accounts = positive_value_exists(yes_please_merge_accounts)
results = voter_email_address_sign_in_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_ownership_is_verified': results['email_ownership_is_verified'],
'email_secret_key_belongs_to_this_voter': results['email_secret_key_belongs_to_this_voter'],
'email_sign_in_attempted': True,
'email_address_found': results['email_address_found'],
'yes_please_merge_accounts': yes_please_merge_accounts,
'voter_we_vote_id_from_secret_key': results['voter_we_vote_id_from_secret_key'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_email_address_verify_view(request): # voterEmailAddressVerify
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
results = voter_email_address_verify_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'email_ownership_is_verified': results['email_ownership_is_verified'],
'email_secret_key_belongs_to_this_voter': results['email_secret_key_belongs_to_this_voter'],
'email_verify_attempted': True,
'email_address_found': results['email_address_found'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_facebook_sign_in_retrieve_view(request): # voterFacebookSignInRetrieve
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_facebook_sign_in_retrieve_for_api(voter_device_id=voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'existing_facebook_account_found': results['existing_facebook_account_found'],
'voter_we_vote_id_attached_to_facebook': results['voter_we_vote_id_attached_to_facebook'],
'voter_we_vote_id_attached_to_facebook_email': results['voter_we_vote_id_attached_to_facebook_email'],
'facebook_retrieve_attempted': True,
'facebook_sign_in_found': results['facebook_sign_in_found'],
'facebook_sign_in_verified': results['facebook_sign_in_verified'],
'facebook_sign_in_failed': results['facebook_sign_in_failed'],
'facebook_secret_key': results['facebook_secret_key'],
'voter_has_data_to_preserve': results['voter_has_data_to_preserve'],
'facebook_user_id': results['facebook_user_id'],
'facebook_profile_image_url_https': results['facebook_profile_image_url_https'],
'we_vote_hosted_profile_image_url_large': results['we_vote_hosted_profile_image_url_large'],
'we_vote_hosted_profile_image_url_medium': results['we_vote_hosted_profile_image_url_medium'],
'we_vote_hosted_profile_image_url_tiny': results['we_vote_hosted_profile_image_url_tiny']
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_facebook_sign_in_save_view(request): # voterFacebookSignInSave
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
save_auth_data = request.GET.get('save_auth_data', False)
save_auth_data = positive_value_exists(save_auth_data)
facebook_access_token = request.GET.get('facebook_access_token', '')
facebook_user_id = request.GET.get('facebook_user_id', '')
facebook_expires_in = request.GET.get('facebook_expires_in', 0)
facebook_signed_request = request.GET.get('facebook_signed_request', '')
save_profile_data = request.GET.get('save_profile_data', False)
save_profile_data = positive_value_exists(save_profile_data)
save_photo_data = request.GET.get('save_photo_data', False)
save_photo_data = positive_value_exists(save_photo_data)
facebook_email = request.GET.get('facebook_email', '')
facebook_first_name = request.GET.get('facebook_first_name', '')
facebook_middle_name = request.GET.get('facebook_middle_name', '')
facebook_last_name = request.GET.get('facebook_last_name', '')
facebook_profile_image_url_https = request.GET.get('facebook_profile_image_url_https', '')
facebook_background_image_url_https = request.GET.get('facebook_background_image_url_https', '')
facebook_background_image_offset_x = request.GET.get('facebook_background_image_offset_x', '')
facebook_background_image_offset_y = request.GET.get('facebook_background_image_offset_y', '')
results = voter_facebook_sign_in_save_for_api(
voter_device_id=voter_device_id,
save_auth_data=save_auth_data,
facebook_access_token=facebook_access_token,
facebook_user_id=facebook_user_id,
facebook_expires_in=facebook_expires_in,
facebook_signed_request=facebook_signed_request,
save_profile_data=save_profile_data,
facebook_email=facebook_email,
facebook_first_name=facebook_first_name,
facebook_middle_name=facebook_middle_name,
facebook_last_name=facebook_last_name,
save_photo_data=save_photo_data,
facebook_profile_image_url_https=facebook_profile_image_url_https,
facebook_background_image_url_https=facebook_background_image_url_https,
facebook_background_image_offset_x=facebook_background_image_offset_x,
facebook_background_image_offset_y=facebook_background_image_offset_y,
)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_save_attempted': True,
'facebook_sign_in_saved': results['facebook_sign_in_saved'],
'save_auth_data': save_auth_data,
'save_profile_data': save_profile_data,
'save_photo_data': save_photo_data,
'minimum_data_saved': results['minimum_data_saved'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_follow_all_organizations_followed_by_organization_view(request):
# voterFollowAllOrganizationsFollowedByOrganization
organization_we_vote_id = request.GET.get('organization_we_vote_id', '')
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
maximum_number_to_follow = get_maximum_number_to_retrieve_from_request(request)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
return voter_follow_all_organizations_followed_by_organization_for_api(
voter_device_id,
organization_we_vote_id=organization_we_vote_id,
maximum_number_to_follow=maximum_number_to_follow, user_agent_string=user_agent_string,
user_agent_object=user_agent_object)
def voter_issue_follow_view(request): # issueFollow
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
issue_we_vote_id = request.GET.get('issue_we_vote_id', False)
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
follow_value = positive_value_exists(request.GET.get('follow', False))
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
ignore_value = positive_value_exists(request.GET.get('ignore', False))
result = voter_issue_follow_for_api(voter_device_id=voter_device_id,
issue_we_vote_id=issue_we_vote_id,
follow_value=follow_value,
ignore_value=ignore_value, user_agent_string=user_agent_string,
user_agent_object=user_agent_object)
result['google_civic_election_id'] = google_civic_election_id
return HttpResponse(json.dumps(result), content_type='application/json')
def voter_location_retrieve_from_ip_view(request): # voterLocationRetrieveFromIP - GeoIP geo location
"""
Take the IP address and return a location (voterLocationRetrieveFromIP)
:param request:
:return:
"""
ip_address = request.GET.get('ip_address', '')
voter_location_results = voter_location_retrieve_from_ip_for_api(request, ip_address)
json_data = {
'success': voter_location_results['success'],
'status': voter_location_results['status'],
'voter_location_found': voter_location_results['voter_location_found'],
'voter_location': voter_location_results['voter_location'],
'ip_address': voter_location_results['ip_address'],
'x_forwarded_for': voter_location_results['x_forwarded_for'],
'http_x_forwarded_for': voter_location_results['http_x_forwarded_for'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_merge_two_accounts_view(request): # voterMergeTwoAccounts
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
email_secret_key = request.GET.get('email_secret_key', '')
facebook_secret_key = request.GET.get('facebook_secret_key', '')
twitter_secret_key = request.GET.get('twitter_secret_key', '')
invitation_secret_key = request.GET.get('invitation_secret_key', '')
results = voter_merge_two_accounts_for_api(voter_device_id=voter_device_id,
email_secret_key=email_secret_key,
facebook_secret_key=facebook_secret_key,
twitter_secret_key=twitter_secret_key,
invitation_secret_key=invitation_secret_key)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_photo_save_view(request): # voterPhotoSave
"""
Save or update a photo for this voter
:param request:
:return:
"""
status = ''
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
try:
facebook_profile_image_url_https = request.GET['facebook_profile_image_url_https']
facebook_profile_image_url_https = facebook_profile_image_url_https.strip()
facebook_photo_variable_exists = True
except KeyError:
facebook_profile_image_url_https = ''
facebook_photo_variable_exists = False
results = voter_photo_save_for_api(voter_device_id,
facebook_profile_image_url_https, facebook_photo_variable_exists)
voter_photo_saved = True if results['success'] else False
if not positive_value_exists(facebook_profile_image_url_https):
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'voter_photo_saved': voter_photo_saved,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
status += results['status'] + ", "
# If here, we saved a valid photo
json_data = {
'status': status,
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'voter_photo_saved': voter_photo_saved,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
def voter_position_retrieve_view(request):
"""
Retrieve all of the details about a single position based on unique identifier. voterPositionRetrieve
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
# ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_we_vote_id = ballot_item_we_vote_id
candidate_we_vote_id = ''
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_we_vote_id = ''
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_we_vote_id = ''
candidate_we_vote_id = ''
measure_we_vote_id = ballot_item_we_vote_id
else:
office_we_vote_id = ''
candidate_we_vote_id = ''
measure_we_vote_id = ''
return voter_position_retrieve_for_api(
voter_device_id=voter_device_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id
)
def voter_position_visibility_save_view(request): # voterPositionVisibilitySave
"""
Change the visibility (between public vs. friends-only) for a single measure or candidate for one voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
visibility_setting = request.GET.get('visibility_setting', False)
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = None
office_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_we_vote_id = None
measure_we_vote_id = ballot_item_we_vote_id
office_we_vote_id = None
elif kind_of_ballot_item == OFFICE:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = ballot_item_we_vote_id
else:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = None
results = voter_position_visibility_save_for_api(
voter_device_id=voter_device_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
visibility_setting=visibility_setting,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_all_positions_retrieve_view(request): # voterAllPositionsRetrieve
"""
Retrieve a list of all positions for one voter, including "is_support", "is_oppose" and "statement_text".
Note that these can either be public positions or private positions.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
google_civic_election_id = request.GET.get('google_civic_election_id', 0)
return voter_all_positions_retrieve_for_api(
voter_device_id=voter_device_id,
google_civic_election_id=google_civic_election_id
)
def voter_position_like_off_save_view(request):
"""
Un-mark the position_like for a single position for one voter (voterPositionLikeOffSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_like_id = request.GET.get('position_like_id', 0)
position_entered_id = request.GET.get('position_entered_id', 0)
return voter_position_like_off_save_for_api(
voter_device_id=voter_device_id, position_like_id=position_like_id, position_entered_id=position_entered_id)
def voter_position_like_on_save_view(request):
"""
Mark the position_like for a single position for one voter (voterPositionLikeOnSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_entered_id = request.GET.get('position_entered_id', 0)
return voter_position_like_on_save_for_api(
voter_device_id=voter_device_id, position_entered_id=position_entered_id)
def voter_position_like_status_retrieve_view(request):
"""
Retrieve whether or not a position_like is marked for position (voterPositionLikeStatusRetrieve)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_entered_id = request.GET.get('position_entered_id', 0)
return voter_position_like_status_retrieve_for_api(
voter_device_id=voter_device_id, position_entered_id=position_entered_id)
def voter_position_comment_save_view(request): # voterPositionCommentSave
"""
Save comment for a single measure or candidate for one voter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
position_we_vote_id = request.GET.get('position_we_vote_id', "")
statement_text = request.GET.get('statement_text', False)
statement_html = request.GET.get('statement_html', False)
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == CANDIDATE:
candidate_we_vote_id = ballot_item_we_vote_id
measure_we_vote_id = None
office_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_we_vote_id = None
measure_we_vote_id = ballot_item_we_vote_id
office_we_vote_id = None
elif kind_of_ballot_item == OFFICE:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = ballot_item_we_vote_id
else:
candidate_we_vote_id = None
measure_we_vote_id = None
office_we_vote_id = None
results = voter_position_comment_save_for_api(
voter_device_id=voter_device_id,
position_we_vote_id=position_we_vote_id,
office_we_vote_id=office_we_vote_id,
candidate_we_vote_id=candidate_we_vote_id,
measure_we_vote_id=measure_we_vote_id,
statement_text=statement_text,
statement_html=statement_html,
)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_opposing_save_view(request):
"""
Save support for a single measure or candidate for one voter (voterOpposingSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_opposing_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_split_into_two_accounts_view(request): # voterSplitIntoTwoAccounts
"""
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
split_off_twitter = request.GET.get('split_off_twitter', True)
results = voter_split_into_two_accounts_for_api(voter_device_id=voter_device_id,
split_off_twitter=split_off_twitter)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_retrieve_view(request): # voterRetrieve
"""
Retrieve a single voter based on voter_device
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
# Figure out the city & state from IP address
voter_location_results = voter_location_retrieve_from_ip_for_api(request)
state_code_from_ip_address = voter_location_results['region']
results = voter_retrieve_for_api(voter_device_id=voter_device_id,
state_code_from_ip_address=state_code_from_ip_address,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
return HttpResponse(json.dumps(results), content_type='application/json')
def voter_sign_out_view(request): # voterSignOut
"""
Sign out from this device. (Delete this voter_device_id from the database, OR if sign_out_all_devices is True,
sign out from all devices.)
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
sign_out_all_devices = request.GET.get('sign_out_all_devices', 0)
if not positive_value_exists(voter_device_id):
success = False
status = "VOTER_SIGN_OUT_VOTER_DEVICE_ID_DOES_NOT_EXIST"
json_data = {
'voter_device_id': voter_device_id,
'sign_out_all_devices': sign_out_all_devices,
'success': success,
'status': status,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
results = voter_sign_out_for_api(voter_device_id=voter_device_id, sign_out_all_devices=sign_out_all_devices)
json_data = {
'voter_device_id': voter_device_id,
'sign_out_all_devices': sign_out_all_devices,
'success': results['success'],
'status': results['status'],
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_stop_opposing_save_view(request):
"""
Save support for a single measure or candidate for one voter (voterStopOpposingSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_stop_opposing_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_stop_supporting_save_view(request):
"""
Save support for a single measure or candidate for one voter (voterStopSupportingSave)
Default to set this as a position for your friends only.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_stop_supporting_save(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_supporting_save_view(request):
"""
Save support for a single measure or candidate for one voter (voterSupportingSave)
Default to set this as a position for your friends only.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
user_agent_string = request.META['HTTP_USER_AGENT']
user_agent_object = get_user_agent(request)
if kind_of_ballot_item == CANDIDATE:
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = None
elif kind_of_ballot_item == MEASURE:
candidate_id = 0
candidate_we_vote_id = None
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
candidate_id = 0
candidate_we_vote_id = None
measure_id = 0
measure_we_vote_id = None
return voter_supporting_save_for_api(voter_device_id=voter_device_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id,
user_agent_string=user_agent_string, user_agent_object=user_agent_object)
def voter_bookmark_off_save_view(request):
"""
Un-mark the bookmark for a single measure, office or candidate for one voter (voterBookmarkOffSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_off_save_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_bookmark_on_save_view(request):
"""
Mark the bookmark for a single measure, office or candidate for one voter (voterBookmarkOnSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_on_save_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_bookmark_status_retrieve_view(request):
"""
Retrieve whether or not a bookmark is marked for an office, candidate or measure based on unique identifier
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
ballot_item_id = request.GET.get('ballot_item_id', 0)
ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)
if kind_of_ballot_item == OFFICE:
office_id = ballot_item_id
office_we_vote_id = ballot_item_we_vote_id
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == CANDIDATE:
office_id = 0
office_we_vote_id = ''
candidate_id = ballot_item_id
candidate_we_vote_id = ballot_item_we_vote_id
measure_id = 0
measure_we_vote_id = ''
elif kind_of_ballot_item == MEASURE:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = ballot_item_id
measure_we_vote_id = ballot_item_we_vote_id
else:
office_id = 0
office_we_vote_id = ''
candidate_id = 0
candidate_we_vote_id = ''
measure_id = 0
measure_we_vote_id = ''
return voter_bookmark_status_retrieve_for_api(
voter_device_id=voter_device_id,
office_id=office_id, office_we_vote_id=office_we_vote_id,
candidate_id=candidate_id, candidate_we_vote_id=candidate_we_vote_id,
measure_id=measure_id, measure_we_vote_id=measure_we_vote_id)
def voter_all_bookmarks_status_retrieve_view(request): # voterAllBookmarksStatusRetrieve
"""
A list of all of the bookmarks that the voter has marked.
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
return voter_all_bookmarks_status_retrieve_for_api(
voter_device_id=voter_device_id)
def voter_twitter_save_to_current_account_view(request): # voterTwitterSaveToCurrentAccount
"""
Saving the results of signing in with Twitter
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
results = voter_twitter_save_to_current_account_for_api(voter_device_id)
json_data = {
'status': results['status'],
'success': results['success'],
'voter_device_id': voter_device_id,
}
return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_update_view(request): # voterUpdate
"""
Update profile-related information for this voter
:param request:
:return:
"""
status = ""
voter_updated = False
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# If we have an incoming GET value for a variable, use it. If we don't pass "False" into voter_update_for_api
# as a signal to not change the variable. (To set variables to False, pass in the string "False".)
try:
facebook_email = request.GET['facebook_email']
facebook_email = facebook_email.strip()
if facebook_email.lower() == 'false':
facebook_email = False
except KeyError:
facebook_email = False
try:
facebook_profile_image_url_https = request.GET['facebook_profile_image_url_https']
facebook_profile_image_url_https = facebook_profile_image_url_https.strip()
if facebook_profile_image_url_https.lower() == 'false':
facebook_profile_image_url_https = False
except KeyError:
facebook_profile_image_url_https = False
first_name = request.GET.get('first_name', False)
if first_name is not False:
first_name = first_name.strip()
if first_name.lower() == 'false':
first_name = False
middle_name = request.GET.get('middle_name', False)
if middle_name is not False:
middle_name = middle_name.strip()
if middle_name.lower() == 'false':
middle_name = False
last_name = request.GET.get('last_name', False)
if last_name is not False:
last_name = last_name.strip()
if last_name.lower() == 'false':
last_name = False
try:
full_name = request.GET['full_name']
full_name = full_name.strip()
if full_name.lower() == 'false':
full_name = False
except KeyError:
full_name = False
try:
name_save_only_if_no_existing_names = request.GET['name_save_only_if_no_existing_names']
name_save_only_if_no_existing_names = name_save_only_if_no_existing_names.strip()
if name_save_only_if_no_existing_names.lower() == 'false':
name_save_only_if_no_existing_names = False
except KeyError:
name_save_only_if_no_existing_names = False
try:
twitter_profile_image_url_https = request.GET['twitter_profile_image_url_https']
twitter_profile_image_url_https = twitter_profile_image_url_https.strip()
if twitter_profile_image_url_https.lower() == 'false':
twitter_profile_image_url_https = False
except KeyError:
twitter_profile_image_url_https = False
try:
interface_status_flags = request.GET['interface_status_flags']
interface_status_flags = interface_status_flags.strip()
interface_status_flags = convert_to_int(interface_status_flags)
except KeyError:
interface_status_flags = False
try:
flag_integer_to_set = request.GET['flag_integer_to_set']
flag_integer_to_set = flag_integer_to_set.strip()
flag_integer_to_set = convert_to_int(flag_integer_to_set)
except KeyError:
flag_integer_to_set = False
try:
flag_integer_to_unset = request.GET['flag_integer_to_unset']
flag_integer_to_unset = flag_integer_to_unset.strip()
flag_integer_to_unset = convert_to_int(flag_integer_to_unset)
except KeyError:
flag_integer_to_unset = False
try:
notification_settings_flags = request.GET['notification_settings_flags']
notification_settings_flags = notification_settings_flags.strip()
notification_settings_flags = convert_to_int(notification_settings_flags)
except KeyError:
notification_settings_flags = False
try:
notification_flag_integer_to_set = request.GET['notification_flag_integer_to_set']
notification_flag_integer_to_set = notification_flag_integer_to_set.strip()
notification_flag_integer_to_set = convert_to_int(notification_flag_integer_to_set)
except KeyError:
notification_flag_integer_to_set = False
try:
notification_flag_integer_to_unset = request.GET['notification_flag_integer_to_unset']
notification_flag_integer_to_unset = notification_flag_integer_to_unset.strip()
notification_flag_integer_to_unset = convert_to_int(notification_flag_integer_to_unset)
except KeyError:
notification_flag_integer_to_unset = False
try:
send_journal_list = request.GET['send_journal_list']
except KeyError:
send_journal_list = False
device_id_results = is_voter_device_id_valid(voter_device_id)
if not device_id_results['success']:
status += "VOTER_DEVICE_ID_NOT_BALLOT " + device_id_results['status']
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': "",
'we_vote_hosted_profile_image_url_medium': "",
'we_vote_hosted_profile_image_url_tiny': "",
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
'voter_donation_history_list': None,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
at_least_one_variable_has_changed = True if \
facebook_email \
or facebook_profile_image_url_https \
or first_name is not False \
or middle_name is not False \
or last_name is not False \
or full_name \
or interface_status_flags is not False \
or flag_integer_to_unset is not False \
or flag_integer_to_set is not False \
or notification_settings_flags is not False \
or notification_flag_integer_to_unset is not False \
or notification_flag_integer_to_set is not False \
or send_journal_list \
else False
voter_manager = VoterManager()
voter_results = voter_manager.retrieve_voter_from_voter_device_id(voter_device_id)
voter_id = voter_results['voter_id']
if not positive_value_exists(voter_id):
status += "VOTER_NOT_FOUND_FROM_DEVICE_ID-VOTER_UPDATE "
json_data = {
'status': status,
'success': False,
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': "",
'we_vote_hosted_profile_image_url_medium': "",
'we_vote_hosted_profile_image_url_tiny': "",
'voter_updated': voter_updated,
'interface_status_flags': interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
'voter_donation_history_list': None,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
voter = voter_results['voter']
# At this point, we have a valid voter
donation_list = donation_history_for_a_voter(voter.we_vote_id)
if not at_least_one_variable_has_changed:
# If here, we want to return the latest data from the voter object
status += "MISSING_VARIABLE-NO_VARIABLES_PASSED_IN_TO_CHANGE "
json_data = {
'status': status,
'success': True,
'voter_device_id': voter_device_id,
'facebook_email': voter.facebook_email,
'facebook_profile_image_url_https': voter.facebook_profile_image_url_https,
'first_name': voter.first_name,
'middle_name': voter.middle_name,
'last_name': voter.last_name,
'twitter_profile_image_url_https': voter.twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': voter.we_vote_hosted_profile_image_url_large,
'we_vote_hosted_profile_image_url_medium': voter.we_vote_hosted_profile_image_url_medium,
'we_vote_hosted_profile_image_url_tiny': voter.we_vote_hosted_profile_image_url_tiny,
'voter_updated': voter_updated,
'interface_status_flags': voter.interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': voter.notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
'voter_donation_history_list': donation_list,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
we_vote_hosted_profile_image_url_large = None
we_vote_hosted_profile_image_url_medium = None
we_vote_hosted_profile_image_url_tiny = None
if twitter_profile_image_url_https:
# Cache original and resized images
# TODO: Replace voter.twitter_id with value from twitter link to voter
cache_results = cache_master_and_resized_image(
voter_we_vote_id=voter.we_vote_id,
twitter_id=voter.twitter_id,
twitter_screen_name=voter.twitter_screen_name,
twitter_profile_image_url_https=twitter_profile_image_url_https,
image_source=TWITTER)
cached_twitter_profile_image_url_https = cache_results['cached_twitter_profile_image_url_https']
we_vote_hosted_profile_image_url_large = cache_results['we_vote_hosted_profile_image_url_large']
we_vote_hosted_profile_image_url_medium = cache_results['we_vote_hosted_profile_image_url_medium']
we_vote_hosted_profile_image_url_tiny = cache_results['we_vote_hosted_profile_image_url_tiny']
if positive_value_exists(cached_twitter_profile_image_url_https):
twitter_profile_image_url_https = cached_twitter_profile_image_url_https
if facebook_profile_image_url_https:
# Cache original and resized images
# TODO: Replace voter.facebook_id with value from facebook link to voter
cache_results = cache_master_and_resized_image(
voter_we_vote_id=voter.we_vote_id,
facebook_user_id=voter.facebook_id,
facebook_profile_image_url_https=facebook_profile_image_url_https,
image_source=FACEBOOK)
cached_facebook_profile_image_url_https = cache_results['cached_facebook_profile_image_url_https']
we_vote_hosted_profile_image_url_large = cache_results['we_vote_hosted_profile_image_url_large']
we_vote_hosted_profile_image_url_medium = cache_results['we_vote_hosted_profile_image_url_medium']
we_vote_hosted_profile_image_url_tiny = cache_results['we_vote_hosted_profile_image_url_tiny']
if positive_value_exists(cached_facebook_profile_image_url_https):
facebook_profile_image_url_https = cached_facebook_profile_image_url_https
if positive_value_exists(voter.first_name) or positive_value_exists(voter.last_name):
saved_first_or_last_name_exists = True
else:
saved_first_or_last_name_exists = False
incoming_first_or_last_name = positive_value_exists(first_name) or positive_value_exists(last_name)
# If a first_name or last_name is coming in, we want to ignore the full_name
if positive_value_exists(full_name) and not positive_value_exists(incoming_first_or_last_name):
incoming_full_name_can_be_processed = True
else:
incoming_full_name_can_be_processed = False
if incoming_full_name_can_be_processed:
# If here we want to parse full_name into first and last
first_name = extract_first_name_from_full_name(full_name)
last_name = extract_last_name_from_full_name(full_name)
if name_save_only_if_no_existing_names:
if saved_first_or_last_name_exists:
first_name = False
last_name = False
voter_manager = VoterManager()
results = voter_manager.update_voter_by_id(
voter_id, facebook_email, facebook_profile_image_url_https,
first_name, middle_name, last_name,
interface_status_flags,
flag_integer_to_set, flag_integer_to_unset,
notification_settings_flags,
notification_flag_integer_to_set, notification_flag_integer_to_unset,
twitter_profile_image_url_https, we_vote_hosted_profile_image_url_large,
we_vote_hosted_profile_image_url_medium, we_vote_hosted_profile_image_url_tiny)
voter = results['voter']
status += results['status']
json_data = {
'status': status,
'success': results['success'],
'voter_device_id': voter_device_id,
'facebook_email': facebook_email,
'facebook_profile_image_url_https': facebook_profile_image_url_https,
'first_name': first_name,
'middle_name': middle_name,
'last_name': last_name,
'twitter_profile_image_url_https': twitter_profile_image_url_https,
'we_vote_hosted_profile_image_url_large': we_vote_hosted_profile_image_url_large,
'we_vote_hosted_profile_image_url_medium': we_vote_hosted_profile_image_url_medium,
'we_vote_hosted_profile_image_url_tiny': we_vote_hosted_profile_image_url_tiny,
'voter_updated': results['voter_updated'],
'interface_status_flags': voter.interface_status_flags,
'flag_integer_to_set': flag_integer_to_set,
'flag_integer_to_unset': flag_integer_to_unset,
'notification_settings_flags': voter.notification_settings_flags,
'notification_flag_integer_to_set': notification_flag_integer_to_set,
'notification_flag_integer_to_unset': notification_flag_integer_to_unset,
'voter_donation_history_list': donation_list,
}
response = HttpResponse(json.dumps(json_data), content_type='application/json')
return response
| {
"repo_name": "jainanisha90/WeVoteServer",
"path": "apis_v1/views/views_voter.py",
"copies": "1",
"size": "93668",
"license": "mit",
"hash": 2277234212951619000,
"line_mean": 48.6912466844,
"line_max": 120,
"alpha_frac": 0.6177349789,
"autogenerated": false,
"ratio": 3.615408368071638,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4733143346971638,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from reaction.controllers import reaction_like_count_for_api, voter_reaction_like_off_save_for_api, \
voter_reaction_like_on_save_for_api, reaction_like_status_retrieve_for_api
import wevote_functions.admin
from wevote_functions.functions import get_voter_device_id, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def reaction_like_count_view(request): # reactionLikeCount
"""
Retrieve the total number of Likes that an item has received, either from the perspective of the voter's
network of friends, or the entire network. (reactionLikeCount)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
liked_item_we_vote_id = request.GET.get('liked_item_we_vote_id', '')
limit_to_voters_network = request.GET.get('limit_to_voters_network', False)
limit_to_voters_network = positive_value_exists(limit_to_voters_network)
return reaction_like_count_for_api(voter_device_id=voter_device_id, liked_item_we_vote_id=liked_item_we_vote_id,
limit_to_voters_network=limit_to_voters_network)
def voter_reaction_like_off_save_view(request): # voterReactionLikeOffSave
"""
Un-mark the reaction for a single position for one voter (voterReactionLikeOffSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
liked_item_we_vote_id = request.GET.get('liked_item_we_vote_id', '')
return voter_reaction_like_off_save_for_api(
voter_device_id=voter_device_id,
liked_item_we_vote_id=liked_item_we_vote_id)
def voter_reaction_like_on_save_view(request): # voterReactionLikeOnSave
"""
Mark the reaction for a single position for one voter (voterReactionLikeOnSave)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
# We track activity_tidbit_we_vote_id so we can get all of the likes under on major item
activity_tidbit_we_vote_id = request.GET.get('activity_tidbit_we_vote_id', '')
liked_item_we_vote_id = request.GET.get('liked_item_we_vote_id', '')
return voter_reaction_like_on_save_for_api(
voter_device_id=voter_device_id,
liked_item_we_vote_id=liked_item_we_vote_id,
activity_tidbit_we_vote_id=activity_tidbit_we_vote_id)
def reaction_like_status_retrieve_view(request): # reactionLikeStatusRetrieve
"""
Retrieve whether or not a reaction is marked for position (reactionLikeStatusRetrieve)
:param request:
:return:
"""
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
liked_item_we_vote_id_list = request.GET.getlist('liked_item_we_vote_id_list[]')
return reaction_like_status_retrieve_for_api(
voter_device_id=voter_device_id, liked_item_we_vote_id_list=liked_item_we_vote_id_list)
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_reaction.py",
"copies": "1",
"size": "3253",
"license": "mit",
"hash": 5483287004495386000,
"line_mean": 46.1449275362,
"line_max": 116,
"alpha_frac": 0.7098063326,
"autogenerated": false,
"ratio": 3.0573308270676693,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4267137159667669,
"avg_score": null,
"num_lines": null
} |
# apis_v1/views/views_voter_utils.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
from voter.models import VoterDeviceLinkManager, VoterManager
from voter_guide.controllers import voter_follow_all_organizations_followed_by_organization_for_api
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, get_maximum_number_to_retrieve_from_request, \
get_voter_device_id, is_voter_device_id_valid, positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
def get_voter_from_request(request, status):
voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id
voter = None
voter_found = False
voter_device_link = None
voter_manager = VoterManager()
voter_device_link_manager = VoterDeviceLinkManager()
link_results = voter_device_link_manager.retrieve_voter_device_link(
voter_device_id=voter_device_id)
if link_results['voter_device_link_found']:
voter_device_link = link_results['voter_device_link']
if positive_value_exists(voter_device_link.voter_id):
results = voter_manager.retrieve_voter_by_id(voter_device_link.voter_id, read_only=False)
if results['voter_found']:
voter = results['voter']
voter_found = True
else:
status += results['status']
else:
status += link_results['status']
return status, voter, voter_found, voter_device_link
| {
"repo_name": "wevote/WeVoteServer",
"path": "apis_v1/views/views_voter_utils.py",
"copies": "1",
"size": "1638",
"license": "mit",
"hash": 1355742992215018000,
"line_mean": 39.95,
"line_max": 103,
"alpha_frac": 0.6984126984,
"autogenerated": false,
"ratio": 3.269461077844311,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4467873776244311,
"avg_score": null,
"num_lines": null
} |
"""API testing."""
try:
from mock import Mock
except:
# python3
from unittest.mock import Mock
from flask import Flask, abort, make_response, request, url_for
from flask import __version__ as flask_version
from flask.json import loads
from flask_resteasy import Api, ApiResponse, Resource, JSONResponse, unpack
import pytest
from .tools import make_foo
def to_json(v):
"""Simple helper to get JSON from object."""
return loads(v.data)
class TestHelpers(object):
"""Helper function to include in other classes."""
def test_unpack(self):
"""Test unpack."""
assert ('hi', 200, {}) == unpack('hi')
assert ('hi', 200, {}) == unpack(('hi', 200))
assert ('hi', 200, {}) == unpack(('hi', None))
assert ('hi', 200, {'X': 'hi'}) == unpack(('hi', 200, {'X': 'hi'}))
def test_resource_without_endpoint(self):
"""Resource without endpoint."""
resource = make_foo()
assert not hasattr(resource, 'endpoint')
def test_using_ApiResponse(self):
"""ApiResponse must be subclassed."""
with Flask(__name__).app_context():
with pytest.raises(NotImplementedError) as err:
ApiResponse().pack('hi', 200)
assert err.value.args[0] == "You must subclass from ApiResponse."
def test_json(self):
"""JSON response."""
with Flask(__name__).app_context():
resp = JSONResponse().pack('hi', 201)
assert 201 == resp.status_code
assert resp.headers['Content-Type'] == 'application/json'
assert loads(resp.data) == "hi"
def test_json_pretty_response(self):
"""Pass pretty print JSON configuration."""
data = {'data': [1, 'two', 3], 'amsg': 'no message'}
with Flask(__name__).app_context():
indent = 4
resp = JSONResponse(sort_keys=True, indent=indent,
separators=(',', ':')).pack(data, 201)
assert 201 == resp.status_code
assert 'application/json' == resp.headers['Content-Type']
assert resp.data.startswith(b'{\n' + b' ' * indent)
lines = resp.data.split(b'\n')
assert 8 == len(lines)
assert lines[4].startswith(b' ' * indent * 2)
assert loads(resp.data) == data
class TestPrefixes(object):
"""Are Blueprint, Api, Resource sequence of prefix and url correct."""
resource_url = '/hi'
@pytest.mark.parametrize('api_prefix', [None, '/api'])
def test_with_app(self, api_prefix):
"""API creation with different prefixes.
API created with app.
"""
expecting_url = (api_prefix or '') + TestPrefixes.resource_url
resource = make_foo()
app = Flask(__name__, static_folder=None)
api = Api(app, prefix=api_prefix)
api.add_resource(resource, TestPrefixes.resource_url, endpoint='hello')
assert 'hello' in api.endpoints
assert resource.endpoint == 'hello'
with app.test_client() as c:
rv = c.get(expecting_url)
assert rv.status_code == 200
assert request.endpoint == 'hello'
with app.test_request_context(expecting_url):
assert url_for('hello') == expecting_url
assert api.url_for(resource) == expecting_url
@pytest.mark.parametrize('api_prefix', [None, '/api'])
def test_with_init_app(self, api_prefix):
"""API creation with different prefixes.
API attached after app creation.
"""
expecting_url = (api_prefix or '') + TestPrefixes.resource_url
resource = make_foo()
api = Api(prefix=api_prefix)
api.add_resource(resource, TestPrefixes.resource_url, endpoint='hello')
app = Flask(__name__, static_folder=None)
api.init_app(app)
assert 'hello' in api.endpoints
assert resource.endpoint == 'hello'
with app.test_client() as c:
rv = c.get(expecting_url)
assert rv.status_code == 200
assert request.endpoint == 'hello'
with app.test_request_context(expecting_url):
assert url_for('hello') == expecting_url
assert api.url_for(resource) == expecting_url
class TestAPI(object):
"""Test the API object.
Is it working as expected?
"""
def test_api(self):
"""Ensure endpoint is created."""
app = Mock()
app.configure_mock(**{'record.side_effect': AttributeError})
api = Api(app, prefix='/foo')
assert api.prefix == '/foo'
def test_api_delayed_initialization(self):
"""API delayed initialization."""
app = Flask(__name__)
api = Api()
resource = make_foo()
api.add_resource(resource, '/', endpoint="hello")
api.init_app(app)
assert resource.endpoint == 'hello'
with app.test_client() as client:
assert client.get('/').status_code == 200
def test_api_on_multiple_url(self):
"""Added resource can have several URLs.
`url_for` will only return the first url
"""
app = Flask(__name__, static_folder=None)
api = Api(app)
resource = make_foo()
api.add_resource(resource, '/api', '/api2')
with app.test_request_context('/api'):
assert api.url_for(resource) == '/api'
with app.test_request_context('/api2'):
assert api.url_for(resource) == '/api'
with app.test_client() as c:
assert to_json(c.get('/api')) == resource.resp
assert to_json(c.get('/api2')) == resource.resp
def test_api_same_endpoint(self):
"""API reuse endpoint.
You can't use the same endpoint, it should throw an error."""
app = Flask(__name__)
api = Api(app, prefix='/v1')
api.add_resource(make_foo(), '/foo', endpoint='baz')
class Bar(Resource):
def get(self):
return 'bar'
major, minor = tuple(map(int, flask_version.split(".")))[:2]
if major == 0 and minor > 10:
with pytest.raises(AssertionError) as err:
api.add_resource(Bar, '/bar', endpoint='baz')
assert err.value.args[0].endswith("existing endpoint function: baz")
else:
with pytest.raises(ValueError) as err:
api.add_resource(Bar, '/bar', endpoint='baz')
assert err.value.args[0].startswith("Endpoint 'baz' is already")
def test_api_pretty(self):
"""Check the JSONResponse for pretty print"""
responder = JSONResponse(sort_keys=True, indent=4,
separators=(',', ':'))
app = Flask(__name__)
api = Api(app, response=responder)
@api.resource('/pretty')
class Foo(Resource):
data = {'data': [1, 'two', 3], 'amsg': 'no message'}
def get(self):
return Foo.data
with app.test_client() as c:
resp = c.get('/pretty')
assert 200 == resp.status_code
assert 'application/json' == resp.headers['Content-Type']
assert resp.data.startswith(b'{\n' + b' ' * 4)
lines = resp.data.split(b'\n')
assert 8 == len(lines)
assert lines[4].startswith(b' ' * 8)
assert loads(resp.data) == Foo.data
def test_api_same_url(self):
"""API same url."""
# TODO Should this pop an error?
app = Flask(__name__)
api = Api(app, prefix='/v1')
@api.resource('/api')
class Foo(Resource):
def get(self):
return 'foo'
@api.resource('/api')
class Bar(Resource):
def get(self):
return 'bar'
with app.test_request_context('/api'):
assert url_for('foo') == url_for('bar')
assert url_for('foo') == '/v1/api'
with app.test_client() as c:
rv = c.get('/v1/api')
assert loads(rv.data) == "foo"
def test_handle_api_error(self):
"""Handle API errors."""
api = Api()
@api.resource('/api', endpoint='api')
class Test(Resource):
def get(self):
abort(404)
app = Flask(__name__)
app.config['DEBUG'] = True
api.init_app(app)
@app.errorhandler(404)
def not_found(err):
rv = {'code': 404, 'msg': 'Not found'}
return api.responder.pack(rv, 404)
with app.test_client() as c:
rv = c.get("/api")
assert rv.status_code == 404
assert rv.headers['Content-Type'] == 'application/json'
data = loads(rv.data.decode())
assert data.get('code') == 404
assert 'msg' in data
def test_handle_non_api_error(self):
"""Handle non API errors."""
app = Flask(__name__)
Api(app)
with app.test_client() as c:
rv = c.get("/foo")
assert rv.status_code == 404
assert rv.headers['Content-Type'] == 'text/html'
def test_url_for(self):
"""url_for test."""
app = Flask(__name__)
api = Api(app)
resource = make_foo()
api.add_resource(resource, '/greeting/<int:idx>')
with app.test_request_context('/foo'):
assert api.url_for(resource, idx=5) == '/greeting/5'
def test_add_the_same_resource_on_different_endpoint(self):
"""Add resource on different endpoints.
We should be able to add the same resource multiple times as long
as we use different endpoints.
"""
app = Flask(__name__)
api = Api(app)
app.config['DEBUG'] = True
class Foo1(Resource):
def get(self):
return 'foo1'
api.add_resource(Foo1, '/foo', endpoint='bar')
api.add_resource(Foo1, '/foo/toto', endpoint='blah')
with app.test_client() as client:
foo1 = client.get('/foo')
assert foo1.data == b'"foo1"'
assert foo1.headers['Content-Type'] == 'application/json'
foo2 = client.get('/foo/toto')
assert foo2.data == b'"foo1"'
def test_add_resource_endpoint(self):
"""Add resource endpoint."""
app = Mock(Flask)
app.view_functions = {}
view = Mock()
api = Api(app)
api.output = Mock()
api.add_resource(view, '/foo', endpoint='bar')
view.as_view.assert_called_with('bar')
def test_resource_decorator(self):
"""Resource decorator."""
app = Flask(__name__)
api = Api(app)
@api.resource('/api')
class Foo(Resource):
def get(self):
return 'foo'
with app.test_client() as c:
c.get('/api').data == 'foo'
def test_add_resource_kwargs(self):
"""Add resource kwargs."""
app = Flask(__name__)
app.config['DEBUG'] = True
api = Api(app)
@api.resource('/bar', defaults={'foo': 'bar'})
class Bar(Resource):
def get(self, foo):
return foo
with app.test_client() as c:
assert loads(c.get('/bar').data) == "bar"
def test_output_unpack(self):
"""Output unpack for response."""
def make_empty_response():
return {'foo': 'bar'}
app = Flask(__name__)
api = Api(app)
with app.test_request_context("/foo"):
wrapper = api.output(make_empty_response)
resp = wrapper()
assert resp.status_code == 200
assert resp.data.decode() == '{"foo": "bar"}'
def test_output_func(self):
"""Output function."""
def make_empty_response():
return make_response('')
app = Flask(__name__)
api = Api(app)
with app.test_request_context("/foo"):
wrapper = api.output(make_empty_response)
resp = wrapper()
assert resp.status_code == 200
assert resp.data.decode() == ''
def test_resource(self):
"""Resource."""
app = Flask(__name__)
resource = Resource()
resource.get = Mock()
with app.test_request_context("/foo"):
resource.dispatch_request()
def test_resource_resp(self):
"""Resource response."""
app = Flask(__name__)
resource = Resource()
resource.get = Mock()
with app.test_request_context("/foo"):
resource.get.return_value = make_response('')
resource.dispatch_request()
def test_resource_error(self):
"""Unimplemented method."""
app = Flask(__name__)
resource = Resource()
with app.test_request_context("/foo"):
with pytest.raises(AssertionError) as err:
resource.dispatch_request()
assert err.value.args[0].startswith('Unimplemented method')
def test_resource_head(self):
"""Check for a HEAD."""
app = Flask(__name__)
resource = Resource()
with app.test_request_context("/foo", method="HEAD"):
with pytest.raises(AssertionError):
resource.dispatch_request()
def test_fr_405(self):
"""HTTP 405 response."""
app = Flask(__name__)
api = Api(app)
foo = make_foo()
api.add_resource(foo, '/ids/<int:id>', endpoint="hello")
with app.test_client() as c:
rv = c.post('/ids/3')
assert rv.status_code == 405
expected_methods = ['HEAD', 'OPTIONS'] + foo.methods
assert rv.headers.get_all('Allow').sort() == expected_methods.sort()
class TestJSON(object):
"""Testing JSON response."""
def test_will_pass_options_to_json(self):
"""Are we getting JSON."""
resource = make_foo()
app = Flask(__name__)
api = Api(app, response=JSONResponse(indent=123))
api.add_resource(resource, '/foo', endpoint='bar')
assert 'indent' in api.responder.json_settings
with app.test_client() as client:
rv = client.get('/foo')
lines = rv.data.splitlines()
lines = [line.decode() for line in lines]
assert lines[0] == "{"
assert lines[1].startswith(' ' * 123) is True
assert lines[2] == "}"
@pytest.mark.xfail
def test_datetime(self):
"""Testing datetime.
What do I expect the datetime.datetime to be? rfc822, iso?
"""
assert False
| {
"repo_name": "jidn/flask-resteasy",
"path": "tests/test_api.py",
"copies": "1",
"size": "14587",
"license": "apache-2.0",
"hash": 5744709129054726000,
"line_mean": 32.0770975057,
"line_max": 80,
"alpha_frac": 0.5414410091,
"autogenerated": false,
"ratio": 4.028445180889257,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00031144144900758657,
"num_lines": 441
} |
# api/tests/base_case.py
import os.path
import unittest
import json
from api import create_app, db
from api.models import User
bucketlists_data = [
'Swimming',
'Reading',
'Travelling',
'Philanthropy',
'Reading',
'Spiritual Enlightment',
'Open Source Contribution',
'Charity',
'Get Married',
'Motivational Speaking',
'Teaching',
'Face my Fears',
'Conquer my Fears',
'Start Blogging',
'Learn a new language',
'Travel abroad',
'Hijjah',
'Own a home',
'Build a bot',
'Racing',
'Invest in shares',
'Stop betting',
'Adopt a child',
'Sponsor a needy student',
'Build Social Profile',
'Riding bikes',
'Own a Rolls Royce',
'Meet Bill Gates',
'Own a Park',
'Learn Martial Arts',
'Go Deep Sea Fishing',
'Learn Salsa'
]
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.test_client = self.app.test_client()
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
# test user details
self.test_username = 'test_user_00'
self.test_password = '@test_usr_pwd#'
self.test_email = 'user_00@gmail.com'
# create default test user
self.test_user = User()
self.test_user.username = self.test_username
self.test_user.password = self.test_password
self.test_user.email = self.test_email
self.test_user.add(self.test_user)
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def get_accept_content_type_headers(self):
return {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
class BucketBaseCase(BaseTestCase):
def login_default_user(self):
login_response = self.test_client.post(
'/auth/login',
headers=self.get_accept_content_type_headers(),
data=json.dumps({
'username': self.test_username,
'password': self.test_password
})
)
login_resp_data = json.loads(login_response.data.decode())
return login_resp_data
def get_authentication_content_type_headers(self):
authentication_headers = self.get_accept_content_type_headers()
token = self.login_default_user()['token']
authentication_headers['Authorization'] = 'Bearer ' + token
return authentication_headers
def create_bucketlists_using_dummy_data(self, bucketlist_data):
response = None
for bucket_name in bucketlist_data:
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': bucket_name
})
)
return response
| {
"repo_name": "Mbarak-Mbigo/cp2_bucketlist",
"path": "api/tests/base_case.py",
"copies": "1",
"size": "2986",
"license": "mit",
"hash": 4292362255340314600,
"line_mean": 27.7115384615,
"line_max": 71,
"alpha_frac": 0.5833891494,
"autogenerated": false,
"ratio": 3.7001239157372985,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4783513065137298,
"avg_score": null,
"num_lines": null
} |
"""API tests"""
from email.utils import formataddr
import pytest
from mail.api import (
context_for_user,
safe_format_recipients,
render_email_templates,
send_messages,
messages_for_recipients,
)
from open_discussions.factories import UserFactory
from open_discussions.test_utils import any_instance_of
from sites.api import get_default_site
pytestmark = [
pytest.mark.django_db,
pytest.mark.usefixtures("email_settings", "authenticated_site"),
]
lazy = pytest.lazy_fixture
@pytest.fixture
def email_settings(settings):
"""Default settings for email tests"""
settings.MAILGUN_RECIPIENT_OVERRIDE = None
def test_safe_format_recipients():
"""Test that we get a list of emailable recipients"""
user = UserFactory.create()
user_no_email = UserFactory.create(email="")
user_no_name = UserFactory.create(profile__name="")
assert safe_format_recipients([user, user_no_email, user_no_name]) == [
(formataddr((user.profile.name, user.email)), user),
(formataddr((None, user_no_name.email)), user_no_name),
]
def test_safe_format_recipients_override(user, settings):
"""Test that the recipient override works"""
settings.MAILGUN_RECIPIENT_OVERRIDE = "admin@localhost"
assert safe_format_recipients([user]) == [("admin@localhost", user)]
@pytest.mark.parametrize("test_user", [None, lazy("user")])
@pytest.mark.parametrize("extra_context", [None, {}, {"other": "value"}])
def test_context_for_user(settings, test_user, extra_context):
"""Tests that context_for_user returns the expected values"""
user_ctx = (
{"user": test_user, "anon_token": any_instance_of(str)} if test_user else {}
)
assert context_for_user(user=test_user, extra_context=extra_context) == {
"base_url": settings.SITE_BASE_URL,
"site_name": get_default_site().title,
**(extra_context or {}),
**user_ctx,
}
def test_render_email_templates(user):
"""Test render_email_templates"""
user.profile.name = "Jane Smith"
context = context_for_user(user=user, extra_context={"url": "http://example.com"})
subject, text_body, html_body = render_email_templates("sample", context)
assert subject == "Welcome Jane Smith"
assert text_body == "html link (http://example.com)"
assert html_body == (
'<style type="text/css">\n'
"a {\n"
" color: red;\n"
"}\n"
"</style>\n"
'<a href="http://example.com">html link</a>\n'
)
def test_messages_for_recipients():
"""Tests that messages_for_recipients works as expected"""
users = UserFactory.create_batch(5)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
assert len(messages) == len(users)
for user, msg in zip(users, messages):
assert user.email in str(msg.to[0])
assert msg.subject == "Welcome {}".format(user.profile.name)
def test_send_message(mailoutbox):
"""Tests that send_messages works as expected"""
users = UserFactory.create_batch(5)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
send_messages(messages)
for message in mailoutbox:
assert message in messages
def test_send_message_failure(mocker):
"""Tests that send_messages logs all exceptions"""
sendmail = mocker.patch("mail.api.AnymailMessage.send", side_effect=ConnectionError)
patched_logger = mocker.patch("mail.api.log")
users = UserFactory.create_batch(2)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
send_messages(messages)
assert sendmail.call_count == len(users)
assert patched_logger.exception.call_count == len(users)
| {
"repo_name": "mitodl/open-discussions",
"path": "mail/api_test.py",
"copies": "1",
"size": "4679",
"license": "bsd-3-clause",
"hash": -6304059307296625000,
"line_mean": 29.1870967742,
"line_max": 88,
"alpha_frac": 0.5883735841,
"autogenerated": false,
"ratio": 3.9485232067510547,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5036896790851054,
"avg_score": null,
"num_lines": null
} |
"""API tests"""
from email.utils import formataddr
import pytest
from mail.v2.api import (
context_for_user,
safe_format_recipients,
render_email_templates,
send_messages,
messages_for_recipients,
build_messages,
build_user_specific_messages,
build_message,
UserMessageProps,
EmailMetadata,
)
from main.test_utils import any_instance_of
from profiles.factories import UserFactory
pytestmark = [pytest.mark.django_db, pytest.mark.usefixtures("email_settings")]
lazy = pytest.lazy_fixture
@pytest.fixture
def email_settings(settings):
"""Default settings for email tests"""
settings.MAILGUN_RECIPIENT_OVERRIDE = None
def test_safe_format_recipients():
"""Test that we get a list of emailable recipients"""
user = UserFactory.create()
user_no_email = UserFactory.create(email="")
user_no_name = UserFactory.create(profile__name="")
assert safe_format_recipients([user, user_no_email, user_no_name]) == [
(formataddr((user.profile.name, user.email)), user),
(formataddr((None, user_no_name.email)), user_no_name),
]
def test_safe_format_recipients_override(user, settings):
"""Test that the recipient override works"""
settings.MAILGUN_RECIPIENT_OVERRIDE = "admin@localhost"
assert safe_format_recipients([user]) == [("admin@localhost", user)]
@pytest.mark.parametrize("test_user", [None, lazy("user")])
@pytest.mark.parametrize("extra_context", [None, {}, {"other": "value"}])
def test_context_for_user(settings, mocker, test_user, extra_context):
"""Tests that context_for_user returns the expected values"""
user_ctx = {"user": test_user} if test_user else {}
mock_get_resource_page_urls = mocker.patch("mail.v2.api.get_resource_page_urls")
assert context_for_user(user=test_user, extra_context=extra_context) == {
"base_url": settings.SITE_BASE_URL,
"site_name": settings.SITE_NAME,
"resource_page_urls": mock_get_resource_page_urls.return_value,
**(extra_context or {}),
**user_ctx,
}
mock_get_resource_page_urls.assert_called_once()
def test_render_email_templates(user):
"""Test render_email_templates"""
user.profile.name = "Jane Smith"
context = context_for_user(user=user, extra_context={"url": "http://example.com"})
subject, text_body, html_body = render_email_templates("sample", context)
assert subject == "Welcome Jane Smith"
assert text_body == "html link (http://example.com)"
assert html_body == (
"<html><head>"
'<style type="text/css">\n'
"p {\n"
" color: blue;\n"
"}\n"
"</style>\n"
"</head><body>"
'<a href="http://example.com" style="color:red">html link</a>'
"</body></html>"
)
def test_messages_for_recipients():
"""Tests that messages_for_recipients works as expected"""
users = UserFactory.create_batch(5)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
assert len(messages) == len(users)
for user, msg in zip(users, messages):
assert user.email in str(msg.to[0])
assert msg.subject == "Welcome {}".format(user.profile.name)
def test_build_messages(mocker):
"""
Tests that build_messages creates message objects for a set of recipients with the correct context
"""
patched_build_message = mocker.patch("mail.v2.api.build_message")
patched_base_context = mocker.patch(
"mail.v2.api.get_base_context", return_value={"base": "context"}
)
patched_get_connection = mocker.patch("mail.v2.api.mail.get_connection")
template_name = "sample"
recipients = ["a@b.com", "c@d.com"]
extra_context = {"extra": "context"}
metadata = EmailMetadata(tags=None, user_variables={"k1": "v1"})
messages = list(
build_messages(template_name, recipients, extra_context, metadata=metadata)
)
assert patched_build_message.call_count == len(recipients)
assert len(messages) == len(recipients)
patched_get_connection.assert_called_once()
patched_base_context.assert_called_once()
for recipient in recipients:
patched_build_message.assert_any_call(
connection=any_instance_of(mocker.Mock),
template_name=template_name,
recipient=recipient,
context={"base": "context", "extra": "context"},
metadata=metadata,
)
def test_build_user_specific_messages(mocker):
"""
Tests that build_user_specific_messages loops through an iterable of user message properties
and builds a message object from each one
"""
patched_build_message = mocker.patch("mail.v2.api.build_message")
mocker.patch("mail.v2.api.get_base_context", return_value={"base": "context"})
mocker.patch("mail.v2.api.mail.get_connection")
template_name = "sample"
user_message_props_iter = [
UserMessageProps(
"a@b.com",
{"first": "context"},
metadata=EmailMetadata(tags=["tag1"], user_variables=None),
),
UserMessageProps("c@d.com", {"second": "context"}),
UserMessageProps("e@f.com"),
]
messages = list(
build_user_specific_messages(template_name, user_message_props_iter)
)
assert len(messages) == len(user_message_props_iter)
for user_message_props in user_message_props_iter:
patched_build_message.assert_any_call(
connection=any_instance_of(mocker.Mock),
template_name=template_name,
recipient=user_message_props.recipient,
context={"base": "context", **user_message_props.context},
metadata=user_message_props.metadata,
)
def test_build_message(mocker, settings):
"""
Tests that build_message correctly builds a message object using the Anymail APIs
"""
settings.MAILGUN_FROM_EMAIL = "from-email@example.com"
settings.BOOTCAMP_REPLY_TO_ADDRESS = "reply-email@example.com"
subject = "subject"
text_body = "body"
html_body = "<p>body</p>"
recipient_email = "recipient@example.com"
template_name = "my_template"
context = {"context_key": "context_value"}
metadata = EmailMetadata(tags=["my-tag"], user_variables={"k1": "v1", "k2": "v2"})
patched_render = mocker.patch(
"mail.v2.api.render_email_templates",
return_value=(subject, text_body, html_body),
)
patched_anymail_message = mocker.patch("mail.v2.api.AnymailMessage")
mock_connection = mocker.Mock()
msg = build_message(
mock_connection, template_name, recipient_email, context, metadata=metadata
)
patched_render.assert_called_once_with(template_name, context)
patched_anymail_message.assert_called_once_with(
subject=subject,
body=text_body,
to=[recipient_email],
from_email=settings.MAILGUN_FROM_EMAIL,
connection=mock_connection,
headers={"Reply-To": settings.BOOTCAMP_REPLY_TO_ADDRESS},
)
msg.attach_alternative.assert_called_once_with(html_body, "text/html")
assert msg.esp_extra == {"o:tag": ["my-tag"], "v:k1": "v1", "v:k2": "v2"}
def test_build_message_optional_params(mocker):
"""Tests that build_message correctly handles optional/None values for certain arguments"""
template_name = "my_template"
patched_render = mocker.patch(
"mail.v2.api.render_email_templates",
return_value=("subject", "body", "<p>body</p>"),
)
mocker.patch("mail.v2.api.AnymailMessage")
msg = build_message(
connection=mocker.Mock(),
template_name=template_name,
recipient="recipient@example.com",
context=None,
metadata=None,
)
patched_render.assert_called_once_with(template_name, {})
# The "esp_extra" property should not have been assigned any value since metadata=None.
# Since AnymailMessage is patched, that means this property should just be a Mock object.
assert isinstance(msg.esp_extra, mocker.Mock)
def test_send_message(mailoutbox):
"""Tests that send_messages works as expected"""
users = UserFactory.create_batch(5)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
send_messages(messages)
for message in mailoutbox:
assert message in messages
def test_send_message_failure(mocker):
"""Tests that send_messages logs all exceptions"""
sendmail = mocker.patch(
"mail.v2.api.AnymailMessage.send", side_effect=ConnectionError
)
patched_logger = mocker.patch("mail.v2.api.log")
users = UserFactory.create_batch(2)
messages = list(
messages_for_recipients(
[
(
recipient,
context_for_user(
user=user, extra_context={"url": "https://example.com"}
),
)
for recipient, user in safe_format_recipients(users)
],
"sample",
)
)
send_messages(messages)
assert sendmail.call_count == len(users)
assert patched_logger.exception.call_count == len(users)
| {
"repo_name": "mitodl/bootcamp-ecommerce",
"path": "mail/v2/api_test.py",
"copies": "1",
"size": "9775",
"license": "bsd-3-clause",
"hash": -2535375619078276000,
"line_mean": 33.5406360424,
"line_max": 102,
"alpha_frac": 0.6212787724,
"autogenerated": false,
"ratio": 3.796116504854369,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9915024581474196,
"avg_score": 0.0004741391560347111,
"num_lines": 283
} |
"""API tests.
"""
import io
import os
from pathlib import Path
import pytest
import rarfile
#
# test start
#
def test_not_rar():
with pytest.raises(rarfile.NotRarFile):
rarfile.RarFile("rarfile.py", "r")
with pytest.raises(rarfile.NotRarFile):
with open("rarfile.py", "rb") as f:
rarfile.RarFile(f, "r")
def test_bad_arc_mode_w():
with pytest.raises(NotImplementedError):
rarfile.RarFile("test/files/rar3-comment-plain.rar", "w")
def test_bad_arc_mode_rb():
with pytest.raises(NotImplementedError):
rarfile.RarFile("test/files/rar3-comment-plain.rar", "rb")
def test_bad_errs():
with pytest.raises(ValueError):
rarfile.RarFile("test/files/rar3-comment-plain.rar", "r", errors="foo")
def test_errors_param():
with open("test/files/rar3-comment-plain.rar", "rb") as f:
data = f.read()
buf = io.BytesIO(data[:17])
with rarfile.RarFile(buf, "r", errors="stop") as rf:
assert rf.namelist() == []
with pytest.raises(rarfile.BadRarFile):
rarfile.RarFile(buf, "r", errors="strict")
def test_bad_open_mode_w():
rf = rarfile.RarFile("test/files/rar3-comment-plain.rar")
with pytest.raises(NotImplementedError):
rf.open("qwe", "w")
def test_bad_open_psw():
rf = rarfile.RarFile("test/files/rar3-comment-psw.rar")
with pytest.raises(rarfile.PasswordRequired):
rf.open("file1.txt")
def test_bad_filelike():
with pytest.raises(ValueError):
rarfile.is_rarfile(bytearray(10))
def test_open_psw_late_rar3():
rf = rarfile.RarFile("test/files/rar3-comment-psw.rar")
d1 = rf.open("file1.txt", "r", "password").read()
d2 = rf.open("file1.txt", "r", b"password").read()
assert d1 == d2
def test_open_psw_late_rar5():
rf = rarfile.RarFile("test/files/rar5-psw.rar")
rf.open("stest1.txt", "r", "password").read()
rf.open("stest1.txt", "r", b"password").read()
def test_open_pathlib_path():
rf = rarfile.RarFile("test/files/rar5-psw.rar")
rf.open(Path("stest1.txt"), "r", "password").read()
def test_read_psw_late_rar3():
rf = rarfile.RarFile("test/files/rar3-comment-psw.rar")
rf.read("file1.txt", "password")
rf.read("file1.txt", b"password")
def test_read_psw_late_rar5():
rf = rarfile.RarFile("test/files/rar5-psw.rar")
rf.read("stest1.txt", "password")
rf.read("stest1.txt", b"password")
def test_open_psw_late():
rf = rarfile.RarFile("test/files/rar5-psw.rar")
with pytest.raises(rarfile.BadRarFile):
rf.read("stest1.txt", "password222")
def test_create_from_pathlib_path():
# Make sure we can open both relative and absolute Paths
rarfile.RarFile(Path("test/files/rar5-psw.rar"))
rarfile.RarFile(Path("test/files/rar5-psw.rar").resolve())
def test_detection():
assert rarfile.is_rarfile("test/files/ctime4.rar.exp") is False
assert rarfile.is_rarfile("test/files/ctime4.rar") is True
assert rarfile.is_rarfile("test/files/rar5-crc.rar") is True
assert rarfile.is_rarfile(Path("test/files/rar5-crc.rar")) is True
assert rarfile.is_rarfile("test/files/_missing_.rar") is False
def test_getinfo():
with rarfile.RarFile("test/files/rar5-crc.rar") as rf:
inf = rf.getinfo("stest1.txt")
assert isinstance(inf, rarfile.RarInfo)
assert rf.getinfo(inf) is inf
with pytest.raises(rarfile.NoRarEntry):
rf.getinfo("missing.txt")
def test_signature_error():
with pytest.raises(rarfile.NotRarFile):
rarfile.RarFile("test/files/ctime4.rar.exp")
def test_signature_error_mem():
data = io.BytesIO(b"x" * 40)
with pytest.raises(rarfile.NotRarFile):
rarfile.RarFile(data)
def test_with():
with rarfile.RarFile("test/files/rar5-crc.rar") as rf:
data = rf.read("stest1.txt")
with rf.open("stest1.txt") as f:
dst = io.BytesIO()
while True:
buf = f.read(7)
if not buf:
break
dst.write(buf)
assert dst.getvalue() == data
def test_readline():
def load_readline(rf, fn):
with rf.open(fn) as f:
tr = io.TextIOWrapper(io.BufferedReader(f))
res = []
while True:
ln = tr.readline()
if not ln:
break
res.append(ln)
return res
rf = rarfile.RarFile("test/files/seektest.rar")
v1 = load_readline(rf, "stest1.txt")
v2 = load_readline(rf, "stest2.txt")
assert len(v1) == 512
assert v1 == v2
def test_printdir(capsys):
rf = rarfile.RarFile("test/files/seektest.rar")
rf.printdir()
res = capsys.readouterr()
assert res.out == "stest1.txt\nstest2.txt\n"
def test_testrar():
rf = rarfile.RarFile("test/files/seektest.rar")
rf.testrar()
def test_iter():
rf = rarfile.RarFile("test/files/seektest.rar")
n1 = rf.namelist()
n2 = [m.filename for m in rf]
assert n1 == n2
def test_testrar_mem():
with open("test/files/seektest.rar", "rb") as f:
arc = f.read()
rf = rarfile.RarFile(io.BytesIO(arc))
rf.testrar()
def test_extract(tmp_path):
ex1 = tmp_path / "extract1"
ex2 = tmp_path / "extract2"
ex3 = tmp_path / "extract3"
os.makedirs(str(ex1))
os.makedirs(str(ex2))
os.makedirs(str(ex3))
rf = rarfile.RarFile("test/files/seektest.rar")
rf.extractall(str(ex1))
assert os.path.isfile(str(ex1 / "stest1.txt")) is True
assert os.path.isfile(str(ex1 / "stest2.txt")) is True
rf.extract("stest1.txt", str(ex2))
assert os.path.isfile(str(ex2 / "stest1.txt")) is True
assert os.path.isfile(str(ex2 / "stest2.txt")) is False
inf = rf.getinfo("stest2.txt")
rf.extract(inf, str(ex3))
assert os.path.isfile(str(ex3 / "stest1.txt")) is False
assert os.path.isfile(str(ex3 / "stest2.txt")) is True
rf.extractall(str(ex2), ["stest1.txt"])
assert os.path.isfile(str(ex2 / "stest1.txt")) is True
rf.extractall(str(ex3), [rf.getinfo("stest2.txt")])
assert os.path.isfile(str(ex3 / "stest2.txt")) is True
ex4 = tmp_path / "extract4"
os.makedirs(str(ex4))
rf.extractall(ex4)
assert os.path.isfile(str(ex4 / "stest1.txt")) is True
assert os.path.isfile(str(ex4 / "stest2.txt")) is True
def test_extract_mem(tmp_path):
ex1 = tmp_path / "extract11"
ex2 = tmp_path / "extract22"
ex3 = tmp_path / "extract33"
os.makedirs(str(ex1))
os.makedirs(str(ex2))
os.makedirs(str(ex3))
with open("test/files/seektest.rar", "rb") as f:
arc = f.read()
rf = rarfile.RarFile(io.BytesIO(arc))
rf.extractall(str(ex1))
assert os.path.isfile(str(ex1 / "stest1.txt")) is True
assert os.path.isfile(str(ex1 / "stest2.txt")) is True
rf.extract("stest1.txt", str(ex2))
assert os.path.isfile(str(ex2 / "stest1.txt")) is True
assert os.path.isfile(str(ex2 / "stest2.txt")) is False
inf = rf.getinfo("stest2.txt")
rf.extract(inf, str(ex3))
assert os.path.isfile(str(ex3 / "stest1.txt")) is False
assert os.path.isfile(str(ex3 / "stest2.txt")) is True
def get_rftype(h):
assert h.is_dir() == h.isdir()
return "".join([
h.is_file() and "F" or "-",
h.is_dir() and "D" or "-",
h.is_symlink() and "L" or "-",
])
def test_infocb():
infos = []
def info_cb(info):
infos.append((info.type, info.needs_password(), get_rftype(info), info._must_disable_hack()))
rf = rarfile.RarFile("test/files/seektest.rar", info_callback=info_cb)
assert infos == [
(rarfile.RAR_BLOCK_MAIN, False, "---", False),
(rarfile.RAR_BLOCK_FILE, False, "F--", False),
(rarfile.RAR_BLOCK_FILE, False, "F--", False),
(rarfile.RAR_BLOCK_ENDARC, False, "---", False)]
rf.close()
infos = []
rf = rarfile.RarFile("test/files/rar5-solid-qo.rar", info_callback=info_cb)
assert infos == [
(rarfile.RAR_BLOCK_MAIN, False, "---", True),
(rarfile.RAR_BLOCK_FILE, False, "F--", False),
(rarfile.RAR_BLOCK_FILE, False, "F--", True),
(rarfile.RAR_BLOCK_FILE, False, "F--", True),
(rarfile.RAR_BLOCK_FILE, False, "F--", True),
(rarfile.RAR_BLOCK_SUB, False, "---", False),
(rarfile.RAR_BLOCK_ENDARC, False, "---", False)]
rf.close()
# pylint: disable=singleton-comparison
def test_rarextfile():
with rarfile.RarFile("test/files/seektest.rar") as rf:
for fn in ("stest1.txt", "stest2.txt"):
with rf.open(fn) as f:
assert f.tell() == 0
assert f.writable() == False
assert f.seekable() == True
assert f.readable() == True
assert f.readall() == rf.read(fn)
def test_is_rarfile():
with rarfile.RarFile("test/files/seektest.rar") as rf:
for fn in ("stest1.txt", "stest2.txt"):
with rf.open(fn) as f:
assert f.tell() == 0
assert f.writable() == False
assert f.seekable() == True
assert f.readable() == True
assert f.readall() == rf.read(fn)
def test_part_only():
info_list = []
def info_cb(info):
info_list.append(info)
with pytest.raises(rarfile.NeedFirstVolume):
with rarfile.RarFile("test/files/rar3-vols.part2.rar") as rf:
pass
with rarfile.RarFile("test/files/rar3-vols.part2.rar", part_only=True, info_callback=info_cb) as rf:
assert len(info_list) == 3
with pytest.raises(rarfile.NeedFirstVolume):
with rarfile.RarFile("test/files/rar5-vols.part2.rar") as rf:
pass
info_list = []
with rarfile.RarFile("test/files/rar5-vols.part2.rar", part_only=True, info_callback=info_cb) as rf:
assert len(info_list) == 5
def test_volume_info():
info_list = []
def info_cb(info):
info_list.append(info)
with rarfile.RarFile("test/files/rar3-vols.part1.rar", info_callback=info_cb) as rf:
assert len(info_list) == 10
info_list = []
with rarfile.RarFile("test/files/rar5-vols.part1.rar", info_callback=info_cb) as rf:
assert len(info_list) == 16
| {
"repo_name": "markokr/rarfile",
"path": "test/test_api.py",
"copies": "1",
"size": "10216",
"license": "isc",
"hash": 226486897763476580,
"line_mean": 28.7842565598,
"line_max": 104,
"alpha_frac": 0.6072826938,
"autogenerated": false,
"ratio": 2.8891402714932126,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.39964229652932126,
"avg_score": null,
"num_lines": null
} |
# api/tests/test_resource_bucketlist.py
import json
from api.tests.base_case import BucketBaseCase, bucketlists_data
new_bucketlist = {
'name': 'Bucketlist_1'
}
update_bucket_list = {
'name': 'My_Bucketlist_1 '
}
new_bucket_item = {
'name' : "Visit a children's home"
}
invalid_token = {
'auth_token': 'akdfjafiqowerijqdfjwfj.qoifjdifjfwejqfdjfdjfqojfdjdjf.qwejdjcajqwesdadkasfafasdfafdsfdf'
}
class TestBucketlist(BucketBaseCase):
def test_create_bucketlist_with_a_valid_token(self):
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps(new_bucketlist)
)
self.assertEqual(response.status_code, 201)
def test_create_bucketlist_with_wrong_data_type(self):
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({'name': 64543})
)
self.assertEqual(response.status_code, 403)
def test_create_bucketlist_with_no_data(self):
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({})
)
self.assertEqual(response.status_code, 400)
def test_create_bucketlist_with_invalid_token(self):
auth_headers = self.get_authentication_content_type_headers()
auth_headers['Authorization'] = 'Bearer' + invalid_token['auth_token']
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=auth_headers,
data=json.dumps(new_bucketlist)
)
self.assertTrue(response.status_code==401)
def test_delete_bucketlist(self):
# create bucketlist
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming'
})
)
self.assertEqual(response.status_code, 201)
# delete created bucket
response = self.test_client.delete(
'/api/v1/bucketlists/1',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 204)
# delete a resource that does not exist
response = self.test_client.delete(
'/api/v1/bucketlists/1',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 404)
def test_retrieve_bucketlists(self):
# Getting bucketlists when none is created
response = self.test_client.get(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 404)
# create bucketlists
self.create_bucketlists_using_dummy_data(bucketlists_data)
# Retrieve created bucketlists
response = self.test_client.get(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 200)
def test_retrieving_bucketlists_with_invalid_token(self):
# create bucketlists
self.create_bucketlists_using_dummy_data(bucketlists_data)
auth_headers = self.get_authentication_content_type_headers()
auth_headers['Authorization'] = 'Bearer' + invalid_token['auth_token']
response = self.test_client.get(
'/api/v1/bucketlists/',
headers=auth_headers,
)
self.assertTrue(response.status_code==401)
def test_retrieving_a_non_existent_bucketlist(self):
self.create_bucketlists_using_dummy_data(bucketlists_data)
response = self.test_client.get(
'/api/v1/bucketlists/150',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 404)
def test_updating_a_non_existent_bucketlist(self):
response = self.test_client.put(
'/api/v1/bucketlists/150',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 404)
def test_updating_a_bucketlist_with_valid_details(self):
# create a bucketlist
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data = json.dumps({
'name': 'Fulfil dreams'
})
)
self.assertTrue(response.status_code==201)
# update created bucketlist
created_object = json.loads(response.data.decode())
response = self.test_client.put(
created_object['url'],
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Fulfil Swimming dream'
})
)
self.assertEqual(response.status_code,200)
def test_bucketlist_item(self):
# create a bucketlist
response = self.test_client.post(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming'
})
)
self.assertEqual(response.status_code, 201)
# get non existent items
response = self.test_client.get(
'/api/v1/bucketlists/1/items/',
headers=self.get_authentication_content_type_headers())
self.assertEqual(response.status_code, 404)
# get non existent item
response = self.test_client.get(
'/api/v1/bucketlists/1/items/4',
headers=self.get_authentication_content_type_headers())
self.assertEqual(response.status_code, 404)
# create a new item without data
response = self.test_client.post(
'/api/v1/bucketlists/1/items/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({})
)
# create a bucketlist item
response = self.test_client.post(
'/api/v1/bucketlists/1/items/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'River Swimming'
})
)
self.assertEqual(response.status_code, 201)
# create an existing bucketlist item
response = self.test_client.post(
'/api/v1/bucketlists/1/items/',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'River Swimming'
})
)
self.assertEqual(response.status_code, 409)
# get bucketitems
response = self.test_client.get(
'/api/v1/bucketlists/1/items/',
headers=self.get_authentication_content_type_headers())
self.assertEqual(response.status_code, 200)
# edit a bucket item
response = self.test_client.put(
'/api/v1/bucketlists/1/items/1',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming pool'
})
)
self.assertEqual(response.status_code, 200)
# edit bucketitem with no data
response = self.test_client.put(
'/api/v1/bucketlists/1/items/1',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({})
)
self.assertEqual(response.status_code, 412)
# edit a non-existent item
response = self.test_client.put(
'/api/v1/bucketlists/1/items/10',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming pool'
})
)
self.assertEqual(response.status_code, 404)
# delete a non existent bucket item
response = self.test_client.delete(
'/api/v1/bucketlists/1/items/10',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming pool'
})
)
self.assertEqual(response.status_code, 404)
# delete an existing item
response = self.test_client.delete(
'/api/v1/bucketlists/1/items/1',
headers=self.get_authentication_content_type_headers(),
data=json.dumps({
'name': 'Swimming pool'
})
)
self.assertEqual(response.status_code, 204)
def test_results_are_paginated(self):
# create 31 bucketlists
self.create_bucketlists_using_dummy_data(bucketlists_data)
# Set limit to 5
response = self.test_client.get(
'/api/v1/bucketlists/?limit=5',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 200)
paginated_results = json.loads(response.data.decode())
# Check buckets on page 1 are 5
self.assertEqual(len(paginated_results['results']), 5)
# Check total count is 7 (number of objects created)
self.assertEqual(paginated_results['count'], 31)
# Check default per page is 20
response = self.test_client.get(
'/api/v1/bucketlists/',
headers=self.get_authentication_content_type_headers()
)
self.assertEqual(response.status_code, 200)
paginated_results = json.loads(response.data.decode())
# Check buckets on page 1 are 20
self.assertEqual(len(paginated_results['results']), 20)
def test_allows_searching_by_name(self):
# create bucketlist
self.create_bucketlists_using_dummy_data(bucketlists_data)
response = self.test_client.get(
'/api/v1/bucketlists/?q=learn',
headers=self.get_authentication_content_type_headers()
)
search_results = json.loads(response.data.decode())
self.assertEqual(response.status_code, 200)
# Check only two bucketlists match search term (Travelling and Cultivate saving Culture)
self.assertEqual(search_results['count'], 3)
# Check results for a search with no match
response = self.test_client.get(
'/api/v1/bucketlists/?q=3433',
headers=self.get_authentication_content_type_headers()
)
search_results = json.loads(response.data.decode())
self.assertEqual(response.status_code, 404)
| {
"repo_name": "Mbarak-Mbigo/cp2_bucketlist",
"path": "api/tests/test_resource_bucketlist.py",
"copies": "1",
"size": "10835",
"license": "mit",
"hash": -7075993557204231000,
"line_mean": 37.2862190813,
"line_max": 107,
"alpha_frac": 0.5971389017,
"autogenerated": false,
"ratio": 3.9342774146695714,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5031416316369571,
"avg_score": null,
"num_lines": null
} |
"""API to access and modify traffic data records.
"""
import base64
import datetime
try:
from urllib.parse import urljoin, urlencode, parse_qs
except ImportError:
from urlparse import urljoin, parse_qs
from urllib import urlencode
import uuid
from flask import *
import six
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
import pytz
from werkzeug.exceptions import NotFound, BadRequest
from trafficdb.models import *
from trafficdb.queries import (
observation_date_range,
observations_for_link,
prepare_resolve_link_aliases,
resolve_link_aliases,
)
__all__ = ['api']
# Create a Blueprint for the web api
api = Blueprint('api', __name__)
# alias api as "app" for use below
app = api
# Maximum number of results to return
PAGE_LIMIT = 20
# Maximum duration to query over in *milliseconds*
MAX_DURATION = 3*24*60*60*1000
JAVASCRIPT_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
def javascript_timestamp_to_datetime(ts):
return JAVASCRIPT_EPOCH + datetime.timedelta(milliseconds=ts)
def datetime_to_javascript_timestamp(dt):
return int((dt - JAVASCRIPT_EPOCH).total_seconds() * 1000)
def uuid_to_urlsafe_id(uuid_text):
id_bytes = base64.urlsafe_b64encode(uuid.UUID(uuid_text).bytes).rstrip(b'=')
try:
return str(id_bytes, 'utf8')
except TypeError:
# On python 2, str doesn't take 2 arguments so use .decode()
return id_bytes.decode('utf8')
def urlsafe_id_to_uuid(urlsafe_id):
if not isinstance(urlsafe_id, bytes):
urlsafe_id = urlsafe_id.encode('utf8')
padding = 4 - (len(urlsafe_id) % 4)
return uuid.UUID(bytes=base64.urlsafe_b64decode(urlsafe_id + b'='*padding)).hex
def verify_link_id(unverified_link_id):
"""Return a Link given the unverified link id from a URL. Aborts with 404
if the link id is invalid or not found.
"""
# Verify link id
try:
link_uuid = urlsafe_id_to_uuid(unverified_link_id)
except:
# If the uuid is invalid, just return 404
return abort(404)
link_q = db.session.query(Link.id, Link.uuid).filter(Link.uuid == link_uuid).limit(1)
try:
return link_q.one()
except NoResultFound:
# 404 on non-existent link
raise NotFound()
# Should be unreachable
assert False
class ApiBadRequest(BadRequest):
def __init__(self, message):
resp = dict(error=dict(message=message))
super(ApiBadRequest, self).__init__(
description=message,
response=make_response(jsonify(resp), 400)
)
@app.route('/')
def index():
return jsonify(dict(
version=1,
resources=dict(
links=url_for('.links', _external=True),
linkAliases=url_for('.link_aliases', _external=True),
),
))
def extend_request_query(base_url, query):
qs = parse_qs(request.query_string)
for k, v in query.items():
if not isinstance(k, bytes):
k = k.encode('utf8')
qs[k] = [v,]
return urljoin(base_url, '?' + urlencode(qs, doseq=True))
@app.route('/links/')
def links():
try:
requested_count = int(request.args.get('count', PAGE_LIMIT))
except ValueError:
# requested count was not an integer
raise ApiBadRequest('count parameter must be an integer')
# Limit count to the maximum we're prepared to give
requested_count = min(PAGE_LIMIT, requested_count)
# Count must be +ve
if requested_count < 0:
raise ApiBadRequest('count parameter must be positive')
# Query link objects
links_q = db.session.query(Link.uuid, func.ST_AsGeoJSON(Link.geom)).order_by(Link.uuid)
unverified_from_id = request.args.get('from')
if unverified_from_id is not None:
try:
from_uuid = urlsafe_id_to_uuid(unverified_from_id)
except:
# If from id is invalid, this is a bad request but raise a 404 to
# avoid exposing details of link id encoding.
raise NotFound()
links_q = links_q.filter(Link.uuid >= from_uuid)
links_q = links_q.limit(requested_count+1)
def row_to_dict(row):
id_string = uuid_to_urlsafe_id(row[0])
properties=dict(
observationsUrl=url_for(
'.observations', unverified_link_id=id_string, _external=True),
url=url_for(
'.link', unverified_link_id=id_string, _external=True),
)
feature = dict(
type='Feature',
id=id_string,
geometry=json.loads(row[1]),
properties=properties,
)
return feature
links = list(row_to_dict(l) for l in links_q)
# How many links to return and do we still have more?
count = min(requested_count, len(links))
# Limit size of output
next_link_id = links[requested_count]['id'] if len(links) > requested_count else None
links = links[:requested_count]
# Form response
page = dict(count = count)
feature_collection = dict(
type='FeatureCollection',
features=links,
properties=dict(page=page),
)
# Form next url if necessary
if next_link_id is not None:
next_args = parse_qs(request.query_string)
next_args['from'.encode('utf8')] = [next_link_id,]
page['next'] = extend_request_query(
url_for('.links', _external=True),
{'from': next_link_id}
)
return jsonify(feature_collection)
@app.route('/links/', methods=['PATCH'])
def patch_links():
# Get request body as JSON document
body = request.get_json()
# Sanitise body
if body is None:
raise ApiBadRequest('request body must be non-empty')
if not isinstance(body, dict):
raise ApiBadRequest('request body must be a JSON object')
# Extract create requests
try:
create_requests = body['create']
except KeyError:
create_requests = []
if not isinstance(create_requests, list) or len(create_requests) > PAGE_LIMIT:
raise ApiBadRequest('create request must be an array of at most {0} items'.format(PAGE_LIMIT))
# Process create requests
created_links = []
for r in create_requests:
geom_geojson = json.dumps(dict(type='LineString', coordinates=r['coordinates']))
created_links.append(Link(
uuid=uuid.uuid4().hex,
geom=func.ST_SetSRID(func.ST_GeomFromGeoJSON(geom_geojson), 4326)))
db.session.add_all(created_links)
def make_create_response(l):
id = uuid_to_urlsafe_id(l.uuid)
return dict(id=id, url=url_for('.link', unverified_link_id=id, _external=True))
create_responses = list(make_create_response(l) for l in created_links)
db.session.commit()
response = dict(create=create_responses)
return jsonify(response)
@app.route('/links/<unverified_link_id>/observations')
def observations(unverified_link_id):
# Verify link id
link_id, link_uuid = verify_link_id(unverified_link_id)
link_urlsafe_id=uuid_to_urlsafe_id(link_uuid)
link_data = dict(id=link_urlsafe_id)
# Work out if a time range has been specified
try:
duration = int(request.args.get('duration', MAX_DURATION))
except ValueError:
# If duration can't be parsed as an integer, that's a bad request
raise ApiBadRequest('duration parameter must be an integer')
# Restrict duration to the maximum we're comfortable with
duration = min(MAX_DURATION, duration)
if duration < 0:
raise ApiBadRequest('duration parameter must be positive')
start_ts = request.args.get('start')
if start_ts is None:
# Get minimum and maximum times
min_d, max_d = observation_date_range(db.session).one()
# Corner case: if there are no observations in the database, it doesn't
# really matter what start time we use so just use now.
if min_d is None:
start_ts = datetime_to_javascript_timestamp(
pytz.utc.localize(datetime.datetime.utcnow()))
else:
start_ts = datetime_to_javascript_timestamp(
max_d - datetime.timedelta(milliseconds=duration))
else:
# Verify start ts is indeed an integer
try:
start_ts = int(start_ts)
except ValueError:
raise ApiBadRequest('start timestamp must be an integer')
# Record parameters of sanitised query
query_params = dict(start=start_ts, duration=duration)
query_params['earlier'] = extend_request_query(
url_for('.observations', unverified_link_id=link_urlsafe_id, _external=True),
dict(start=start_ts-duration),
)
query_params['later'] = extend_request_query(
url_for('.observations', unverified_link_id=link_urlsafe_id, _external=True),
dict(start=start_ts+duration),
)
start_date = javascript_timestamp_to_datetime(start_ts)
end_date = javascript_timestamp_to_datetime(start_ts + duration)
data = {}
for type in ObservationType:
values = []
q = observations_for_link(db.session, link_id, type, start_date, end_date)
for obs in q:
values.append((datetime_to_javascript_timestamp(obs.observed_at), obs.value))
data[type.value] = dict(values=values)
response = dict(link=link_data, data=data, query=query_params)
return jsonify(response)
@app.route('/links/<unverified_link_id>/')
def link(unverified_link_id):
link_id, link_uuid = verify_link_id(unverified_link_id)
link_url_id = uuid_to_urlsafe_id(link_uuid)
# Query aliases
aliases = list(r[0] for r in
db.session.query(LinkAlias.name).filter(LinkAlias.link_id==link_id))
# Query geometry
geom = json.loads(
db.session.query(func.ST_AsGeoJSON(Link.geom)).filter(Link.id==link_id).one()[0]
)
response = dict(
type='Feature',
id=link_url_id,
geometry=geom,
properties=dict(
observationsUrl=url_for('.observations', unverified_link_id=link_url_id, _external=True),
aliases=aliases,
),
)
return jsonify(response)
@app.route('/aliases/')
def link_aliases():
try:
requested_count = int(request.args.get('count', PAGE_LIMIT))
except ValueError:
# requested count was not an integer
raise ApiBadRequest('count parameter must be an integer')
# Limit count to the maximum we're prepared to give
requested_count = min(PAGE_LIMIT, requested_count)
# Count must be +ve
if requested_count < 0:
raise ApiBadRequest('count parameter must be positive')
# Query link objects
aliases_q = db.session.query(LinkAlias.name, Link.uuid).join(Link).\
order_by(LinkAlias.name)
from_id = request.args.get('from', None)
if from_id is not None:
aliases_q = aliases_q.filter(LinkAlias.name >= str(from_id))
aliases_q = aliases_q.limit(requested_count+1)
def row_to_item(row):
link_id = uuid_to_urlsafe_id(row[1])
link_url = url_for('.link', unverified_link_id=link_id, _external=True)
return dict(id=row[0], linkId=link_id, linkUrl=link_url)
aliases = list(row_to_item(l) for l in aliases_q)
# How many aliases to return and do we still have more?
count = min(requested_count, len(aliases))
# Limit size of output
next_link_id = aliases[requested_count]['id'] if len(aliases) > requested_count else None
aliases = aliases[:requested_count]
# Form response
page = dict(count = count)
# Form next url if necessary
if next_link_id is not None:
next_args = parse_qs(request.query_string)
next_args['from'.encode('utf8')] = [next_link_id,]
page['next'] = extend_request_query(
url_for('.link_aliases', _external=True),
{'from': next_link_id}
)
return jsonify(dict(aliases=aliases, page=page))
@app.route('/aliases/resolve', methods=['POST'])
def link_aliases_resolve():
# Request body should be JSON
req_body = request.get_json()
if req_body is None:
raise ApiBadRequest('request body must be non-empty')
# Retrieve and sanitise alias list
try:
aliases = req_body['aliases']
except KeyError:
raise ApiBadRequest('request body must have an "aliases" field')
if not isinstance(aliases, list):
raise ApiBadRequest('aliases must be an array')
if len(aliases) > PAGE_LIMIT:
raise ApiBadRequest('aliases may only have at most {0} entries'.format(PAGE_LIMIT))
if any(not isinstance(a, six.string_types) for a in aliases):
raise ApiBadRequest('aliases must contain only strings')
def link_from_uuid(link_uuid):
if link_uuid is None:
return None
link_id = uuid_to_urlsafe_id(link_uuid)
return dict(id=link_id, url=url_for('.link', unverified_link_id=link_id, _external=True))
db.session.commit() # HACK: seems that temporary table sometimes is not created without this
tmp_table = prepare_resolve_link_aliases(db.session)
q = resolve_link_aliases(db.session, aliases, tmp_table)
resolutions = list((r[0], link_from_uuid(r[2])) for r in q)
response = dict(resolutions=resolutions)
return jsonify(response)
@app.route('/aliases/', methods=['PATCH'])
def patch_aliases():
# Get request body as JSON document
body = request.get_json()
# Sanitise body
if body is None:
raise ApiBadRequest('request body must be non-empty')
if not isinstance(body, dict):
raise ApiBadRequest('request body must be a JSON object')
# Extract create requests
try:
create_requests = body['create']
except KeyError:
create_requests = []
if not isinstance(create_requests, list) or len(create_requests) > PAGE_LIMIT:
raise ApiBadRequest('create request must be an array of at most {0} items'.format(PAGE_LIMIT))
# Process create requests
created_aliases = []
for r in create_requests:
try:
req_name, req_link = r['name'], r['link']
assert isinstance(req_name, six.string_types)
assert isinstance(req_link, six.string_types)
except:
raise ApiBadRequest('create request number {0} is malformed'.format(
len(created_aliases)+1))
try:
link_id, _ = verify_link_id(req_link)
except NotFound:
raise ApiBadRequest(
'create request number {0} references non-existent link "{1}"'.format(
len(created_aliases)+1, req_link))
created_aliases.append(LinkAlias(name=req_name, link_id=link_id))
db.session.add_all(created_aliases)
try:
db.session.commit()
except IntegrityError:
raise ApiBadRequest('invalid request (perhaps identical alias names?)')
response = dict(create={ 'status': 'ok', 'count': len(created_aliases) })
return jsonify(response)
| {
"repo_name": "rjw57/trafficdb",
"path": "trafficdb/blueprint/api.py",
"copies": "1",
"size": "15044",
"license": "mit",
"hash": 545257173108239940,
"line_mean": 32.806741573,
"line_max": 102,
"alpha_frac": 0.640720553,
"autogenerated": false,
"ratio": 3.7136509503826214,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4854371503382621,
"avg_score": null,
"num_lines": null
} |
"""API to persist and read upload data metrics"""
import os
import sqlite3
DATABASE_FILENAME = os.path.expanduser('~/pypic.db')
def create_upload_table():
"""Create the necessary database objects for upload monitoring and
persistent data regarding all things video uploads
"""
db_connection = sqlite3.connect(DATABASE_FILENAME)
cursor = db_connection.cursor()
if not len(
cursor.execute(
'select * from sqlite_master where name = ?',
('uploads',)
).fetchall()):
cursor.execute(
'''create table uploads (
date_created text,
file_name text,
uploaded integer,
other_info text
)'''
)
def insert_upload_data(file_name, date_created, is_uploaded, other_info):
"""Insert the necessary data to reflect whether or not a video was
uploaded
"""
db_connection = sqlite3.connect(DATABASE_FILENAME)
cursor = db_connection.cursor()
cursor.execute(
'insert into uploads values (?, ?, ?, ?)',
(str(date_created), file_name, int(is_uploaded), other_info)
)
db_connection.commit()
db_connection.close()
| {
"repo_name": "tstringer/pypic",
"path": "data/upload.py",
"copies": "1",
"size": "1228",
"license": "mit",
"hash": 8118761760214176000,
"line_mean": 27.5581395349,
"line_max": 73,
"alpha_frac": 0.5960912052,
"autogenerated": false,
"ratio": 4.401433691756273,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5497524896956272,
"avg_score": null,
"num_lines": null
} |
# api to remote mysql web server
import logging
from .utils.SpiderUrlApi import SpiderUrlApi
from . import defaults
from .logger import sm_log
def get_mysql_from_settings(settings):
"""Returns a mysql client instance from given Scrapy settings object.
This function uses ``get_client`` to instantiate the client and uses
``defaults.MYSQL_PARAMS`` global as defaults values for the parameters. You
can override them using the ``MYSQL_PARAMS`` setting.
Parameters
----------
settings : Settings
A scrapy settings object. See the supported settings below.
Returns
-------
server
Redis client instance.
Other Parameters
----------------
MYSQL_URL : str, optional
Server connection URL.
MYSQL_HOST : str, optional
Server host.
MYSQL_PORT : str, optional
Server port.
MYSQL_ENCODING : str, optional
Data encoding.
MYSQL_PARAMS : dict, optional
Additional client parameters.
"""
params = defaults.MYSQL_REMOTE_PARAMS.copy()
params.update(settings.getdict('MYSQL_URL_REMOTE_PARAMS'))
return get_mysql(**params)
# Backwards compatible alias.
from_settings = get_mysql_from_settings
def get_mysql(**kwargs):
"""Returns a mysql client instance.
Parameters
----------
mysql_cls : class, optional
Defaults to ``mysql.StrictRedis``.
url : str, optional
If given, ``mysql_cls.from_url`` is used to instantiate the class.
**kwargs
Extra parameters to be passed to the ``mysql_cls`` class.
Returns
-------
server
Redis client instance.
"""
server = kwargs['SERVER']
auth_code = kwargs['AUTH_CODE']
url_server = SpiderUrlApi(server, auth_code)
return url_server
class Connection(object):
def __init__(self):
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
conn = from_settings(settings)
self.conn = conn
def update_status(self, id, status=10, content=None):
data = dict(id=id, status=status)
if content is not None:
data['content'] = ""
resp = self.conn.update(data)
code = resp['code']
if code != 0:
msg = resp['msg']
data = resp['data']
sm_log.error("error to update status of id[%s] with code: [%s], msg:[%s], data:[%s]" % (
id, status, msg, data))
conn = Connection()
| {
"repo_name": "mavarick/scrapy-mysql",
"path": "scrapy_mysql/connection.py",
"copies": "1",
"size": "2486",
"license": "mit",
"hash": 7263601706212468000,
"line_mean": 25.7311827957,
"line_max": 100,
"alpha_frac": 0.6166532582,
"autogenerated": false,
"ratio": 4.1433333333333335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00010646225912913872,
"num_lines": 93
} |
"""API to the genotype store"""
import logging
from datetime import datetime
from typing import Optional
from alchy import Manager
from sqlalchemy import func, or_
from genotype.store.models import SNP, Analysis, Genotype, Model, Plate, Sample
log = logging.getLogger(__name__)
def connect(uri: str) -> Manager:
log.debug("open connection to database: %s", uri)
manager = Manager(config=dict(SQLALCHEMY_DATABASE_URI=uri), Model=Model)
return manager
def complete():
"""Return samples that have been annotated completely."""
query = (
Sample.query.join(Sample.analyses)
.group_by(Analysis.sample_id)
.having(func.count(Analysis.sample_id) == 2)
)
return query
def pending():
"""Return samples to be matched."""
query = complete().filter(Sample.status == None, Sample.sex != None)
return query
def failing():
"""Return all samples that have failed some check."""
query = Sample.query.filter_by(status="fail")
return query
def get_samples_after(date: datetime):
"""Return samples created since date"""
query = Sample.query.filter(Sample.created_at > date)
return query
def passing():
"""Return all samples that have passed the checks."""
query = Sample.query.filter_by(status="pass")
return query
def incomplete(query=None, since=None):
"""Return samples that haven't been annotated completely."""
base_query = query or Sample.query
base_query = base_query.join(Sample.analyses).order_by(Analysis.created_at.desc())
# filter analyses on which are lacking genotypes
base_query = base_query.group_by(Analysis.sample_id).having(func.count(Analysis.sample_id) < 2)
if since:
base_query = base_query.filter(Analysis.created_at > since)
return base_query
def missing_genotypes(session, analysis_type, since=None):
"""Return analyses where the complementing genotype info is missing."""
subquery = (
session.query(Analysis, Sample.sex.label("sample_sex"))
.join(Analysis.sample)
.order_by(Analysis.created_at.desc())
.group_by(Analysis.sample_id)
.having(func.count(Analysis.sample_id) < 2)
.subquery()
)
query = session.query(subquery).filter(subquery.c.type != analysis_type)
if since:
query = query.filter(Analysis.created_at > since)
return query
def missing_sex(since=None):
"""Return Samples lacking sex but having all genotypes."""
nosex_filter = or_(Sample.sex == None, Analysis.sex == None)
query = (
Sample.query.join(Sample.analyses)
.order_by(Analysis.created_at.desc())
.filter(nosex_filter)
.group_by(Analysis.sample_id)
.having(func.count(Analysis.sample_id) == 2)
)
if since:
query = query.filter(Analysis.created_at > since)
return query
def snps():
"""Return all the SNPs in order."""
query = SNP.query.order_by("id")
return query
def sample(sample_id: str, notfound_cb=None) -> Sample:
"""Get sample from database and abort context if not found."""
sample_obj = Sample.query.get(sample_id)
if sample_obj is None:
log.error("sample id not found in database: %s", sample_id)
return notfound_cb() if notfound_cb else notfound_cb
return sample_obj
def samples(plate_id=None, no_status=False):
"""List samples in the database."""
query = Sample.query
if plate_id:
query = query.join(Sample.analyses).filter(Analysis.source.like("%{}\_%".format(plate_id)))
if no_status:
query = query.filter(Sample.status == None)
return query
def plates():
"""Return the plate ids loaded in the database."""
query = Plate.query
return query
def plate(plate_id):
"""Return the plate with the given id."""
query = Plate.query.filter_by(plate_id=plate_id)
return query.first()
def delete_analysis(db, old_analysis, log=True):
"""Delete an analysis with related genotypes.
Args:
old_analysis (Analysis): analysis record to be deleted
log (Optional[bool]): store log in sample record
"""
# store away info about currently loaded analysis
log_msg = """----------AUTO: replace analysis----------
Source: {analysis.source}
Type: {analysis.type}
Sex: {analysis.sex}
---------- AUTO: end replace ----------\n""".format(
analysis=old_analysis
)
if old_analysis.sample.comment:
old_analysis.sample.comment += log_msg
else:
old_analysis.sample.comment = log_msg
# remove old analysis data
old_analysis.delete()
db.commit()
def add_analysis(db: Manager, new_analysis: Analysis, replace: bool = False) -> Optional[Analysis]:
"""Add a new analysis to the database.
The analysis record should only have the `sample_id` field filled in.
A sample object will be fetched from the database or created.
Args:
new_analysis (Analysis): analysis record to be added
replace (Optional[bool]): replace existing record with new one
Returns:
Analysis/None: the analysis if successful, otherwise `None`
"""
analysis_kwargs = dict(sample_id=new_analysis.sample_id, type=new_analysis.type)
old_analysis = analysis(**analysis_kwargs).first()
if old_analysis:
log.debug("found old analysis: %s-%s", new_analysis.sample_id, new_analysis.type)
if replace:
log.info("deleting old analysis: %s-%s", new_analysis.sample_id, new_analysis.type)
delete_analysis(db, old_analysis)
else:
return None
# check if sample already in database
sample_obj = Sample.query.get(new_analysis.sample_id)
if sample_obj:
log.debug("found sample in database")
new_analysis.sample = sample_obj
else:
sample_obj = Sample(id=new_analysis.sample_id)
new_analysis.sample = sample_obj
db.add_commit(new_analysis)
return new_analysis
def analysis(sample_id, type):
"""Ask the database for a single analysis record.
You can preferably call `.first()` on the returned value to get the
analysis record or `None` if not found in the database.
Args:
sample_id (str): unique sample id
type (str): choice of analysis type [genotype, sequence]
Returns:
query: SQLAlchemy query object
"""
query = Analysis.query.filter_by(sample_id=sample_id, type=type)
return query
def genotypes_by_analysis(session, analysis_id):
"""Ask the database for the genotype records with a specific analysis id.
Args:
analysis_id (str): unique analysis id
Returns:
query: SQLAlchemy query object
"""
query = session.query(Genotype).filter(Genotype.analysis_id == analysis_id).all()
return query
def analysis_by_sample(session, sample_id):
"""Ask the database for the genotype records with a specific analysis id.
Args:
sample_id (str): unique sample id
Returns:
query: SQLAlchemy query object
"""
query = session.query(Analysis).filter(Analysis.sample_id == sample_id).all()
return query
| {
"repo_name": "Clinical-Genomics/taboo",
"path": "genotype/store/api.py",
"copies": "1",
"size": "7126",
"license": "mit",
"hash": 4028818856359431700,
"line_mean": 29.0675105485,
"line_max": 99,
"alpha_frac": 0.6595565535,
"autogenerated": false,
"ratio": 3.827067669172932,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4986624222672932,
"avg_score": null,
"num_lines": null
} |
# API upgrade business logic.
import copy
import re
from tools.api_proto_plugin import traverse
from tools.api_proto_plugin import visitor
from tools.protoxform import options
from tools.protoxform import utils
from envoy.annotations import resource_pb2
from udpa.annotations import migrate_pb2
from google.api import annotations_pb2
ENVOY_API_TYPE_REGEX_STR = 'envoy_api_(msg|enum_value|field|enum)_([\w\.]+)'
ENVOY_COMMENT_WITH_TYPE_REGEX = re.compile('<%s>|:ref:`%s`' %
(ENVOY_API_TYPE_REGEX_STR, ENVOY_API_TYPE_REGEX_STR))
class UpgradeVisitor(visitor.Visitor):
"""Visitor to generate an upgraded proto from a FileDescriptor proto.
See visitor.Visitor for visitor method docs comments.
"""
def __init__(self, typedb, envoy_internal_shadow):
self._typedb = typedb
self._envoy_internal_shadow = envoy_internal_shadow
def _UpgradedComment(self, c):
def UpgradeType(match):
# We're upgrading a type within a RST anchor reference here. These are
# stylized and match the output format of tools/protodoc. We need to do
# some special handling of field/enum values, and also the normalization
# that was performed in v2 for envoy.api.v2 types.
label_ref_type, label_normalized_type_name, section_ref_type, section_normalized_type_name = match.groups(
)
if label_ref_type is not None:
ref_type = label_ref_type
normalized_type_name = label_normalized_type_name
else:
ref_type = section_ref_type
normalized_type_name = section_normalized_type_name
if ref_type == 'field' or ref_type == 'enum_value':
normalized_type_name, residual = normalized_type_name.rsplit('.', 1)
else:
residual = ''
type_name = 'envoy.' + normalized_type_name
api_v2_type_name = 'envoy.api.v2.' + normalized_type_name
if type_name in self._typedb.types:
type_desc = self._typedb.types[type_name]
else:
# We need to deal with envoy.api.* normalization in the v2 API. We won't
# need this in v3+, so rather than churn docs, we just have this workaround.
type_desc = self._typedb.types[api_v2_type_name]
repl_type = type_desc.next_version_type_name[len(
'envoy.'):] if type_desc.next_version_type_name else normalized_type_name
# TODO(htuch): this should really either go through the type database or
# via the descriptor pool and annotations, but there are only two of these
# we need for the initial v2 -> v3 docs cut, so hard coding for now.
# Tracked at https://github.com/envoyproxy/envoy/issues/9734.
if repl_type == 'config.route.v3.RouteAction':
if residual == 'host_rewrite':
residual = 'host_rewrite_literal'
elif residual == 'auto_host_rewrite_header':
residual = 'auto_host_rewrite'
new_ref = 'envoy_api_%s_%s%s' % (ref_type, repl_type, '.' + residual if residual else '')
if label_ref_type is not None:
return '<%s>' % new_ref
else:
return ':ref:`%s`' % new_ref
return re.sub(ENVOY_COMMENT_WITH_TYPE_REGEX, UpgradeType, c)
def _UpgradedPostMethod(self, m):
return re.sub(r'^/v2/', '/v3/', m)
# Upgraded type using canonical type naming, e.g. foo.bar.
def _UpgradedTypeCanonical(self, t):
if not t.startswith('envoy'):
return t
type_desc = self._typedb.types[t]
if type_desc.next_version_type_name:
return type_desc.next_version_type_name
return t
# Upgraded type using internal type naming, e.g. .foo.bar.
def _UpgradedType(self, t):
if not t.startswith('.envoy'):
return t
return '.' + self._UpgradedTypeCanonical(t[1:])
def _Deprecate(self, proto, field_or_value):
"""Deprecate a field or value in a message/enum proto.
Args:
proto: DescriptorProto or EnumDescriptorProto message.
field_or_value: field or value inside proto.
"""
if self._envoy_internal_shadow:
field_or_value.name = 'hidden_envoy_deprecated_' + field_or_value.name
else:
reserved = proto.reserved_range.add()
reserved.start = field_or_value.number
reserved.end = field_or_value.number + 1
proto.reserved_name.append(field_or_value.name)
options.AddHideOption(field_or_value.options)
def _Rename(self, proto, migrate_annotation):
"""Rename a field/enum/service/message
Args:
proto: DescriptorProto or corresponding proto message
migrate_annotation: udpa.annotations.MigrateAnnotation message
"""
if migrate_annotation.rename:
proto.name = migrate_annotation.rename
migrate_annotation.rename = ""
def _OneofPromotion(self, msg_proto, field_proto, migrate_annotation):
"""Promote a field to a oneof.
Args:
msg_proto: DescriptorProto for message containing field.
field_proto: FieldDescriptorProto for field.
migrate_annotation: udpa.annotations.FieldMigrateAnnotation message
"""
if migrate_annotation.oneof_promotion:
oneof_index = -1
for n, oneof_decl in enumerate(msg_proto.oneof_decl):
if oneof_decl.name == migrate_annotation.oneof_promotion:
oneof_index = n
if oneof_index == -1:
oneof_index = len(msg_proto.oneof_decl)
oneof_decl = msg_proto.oneof_decl.add()
oneof_decl.name = migrate_annotation.oneof_promotion
field_proto.oneof_index = oneof_index
migrate_annotation.oneof_promotion = ""
def VisitService(self, service_proto, type_context):
upgraded_proto = copy.deepcopy(service_proto)
for m in upgraded_proto.method:
if m.options.HasExtension(annotations_pb2.http):
http_options = m.options.Extensions[annotations_pb2.http]
# TODO(htuch): figure out a more systematic approach using the type DB
# to service upgrade.
http_options.post = self._UpgradedPostMethod(http_options.post)
m.input_type = self._UpgradedType(m.input_type)
m.output_type = self._UpgradedType(m.output_type)
if service_proto.options.HasExtension(resource_pb2.resource):
upgraded_proto.options.Extensions[resource_pb2.resource].type = self._UpgradedTypeCanonical(
service_proto.options.Extensions[resource_pb2.resource].type)
return upgraded_proto
def VisitMessage(self, msg_proto, type_context, nested_msgs, nested_enums):
upgraded_proto = copy.deepcopy(msg_proto)
if upgraded_proto.options.deprecated and not self._envoy_internal_shadow:
options.AddHideOption(upgraded_proto.options)
options.SetVersioningAnnotation(upgraded_proto.options, type_context.name)
# Mark deprecated fields as ready for deletion by protoxform.
for f in upgraded_proto.field:
if f.options.deprecated:
self._Deprecate(upgraded_proto, f)
if self._envoy_internal_shadow:
# When shadowing, we use the upgraded version of types (which should
# themselves also be shadowed), to allow us to avoid unnecessary
# references to the previous version (and complexities around
# upgrading during API boosting).
f.type_name = self._UpgradedType(f.type_name)
else:
# Make sure the type name is erased so it isn't picked up by protoxform
# when computing deps.
f.type_name = ""
else:
f.type_name = self._UpgradedType(f.type_name)
if f.options.HasExtension(migrate_pb2.field_migrate):
field_migrate = f.options.Extensions[migrate_pb2.field_migrate]
self._Rename(f, field_migrate)
self._OneofPromotion(upgraded_proto, f, field_migrate)
# Upgrade nested messages.
del upgraded_proto.nested_type[:]
upgraded_proto.nested_type.extend(nested_msgs)
# Upgrade enums.
del upgraded_proto.enum_type[:]
upgraded_proto.enum_type.extend(nested_enums)
return upgraded_proto
def VisitEnum(self, enum_proto, type_context):
upgraded_proto = copy.deepcopy(enum_proto)
for v in upgraded_proto.value:
if v.options.deprecated:
# We need special handling for the zero field, as proto3 needs some value
# here.
if v.number == 0 and not self._envoy_internal_shadow:
v.name = 'DEPRECATED_AND_UNAVAILABLE_DO_NOT_USE'
else:
# Mark deprecated enum values as ready for deletion by protoxform.
self._Deprecate(upgraded_proto, v)
elif v.options.HasExtension(migrate_pb2.enum_value_migrate):
self._Rename(v, v.options.Extensions[migrate_pb2.enum_value_migrate])
return upgraded_proto
def VisitFile(self, file_proto, type_context, services, msgs, enums):
upgraded_proto = copy.deepcopy(file_proto)
# Upgrade imports.
upgraded_proto.dependency[:] = [
dependency for dependency in upgraded_proto.dependency
if dependency not in ("udpa/annotations/migrate.proto")
]
# Upgrade package.
upgraded_proto.package = self._typedb.next_version_protos[upgraded_proto.name].qualified_package
upgraded_proto.name = self._typedb.next_version_protos[upgraded_proto.name].proto_path
upgraded_proto.options.ClearExtension(migrate_pb2.file_migrate)
# Upgrade comments.
for location in upgraded_proto.source_code_info.location:
location.leading_comments = self._UpgradedComment(location.leading_comments)
location.trailing_comments = self._UpgradedComment(location.trailing_comments)
for n, c in enumerate(location.leading_detached_comments):
location.leading_detached_comments[n] = self._UpgradedComment(c)
# Upgrade services.
del upgraded_proto.service[:]
upgraded_proto.service.extend(services)
# Upgrade messages.
del upgraded_proto.message_type[:]
upgraded_proto.message_type.extend(msgs)
# Upgrade enums.
del upgraded_proto.enum_type[:]
upgraded_proto.enum_type.extend(enums)
return upgraded_proto
def V3MigrationXform(envoy_internal_shadow, file_proto):
"""Transform a FileDescriptorProto from v2[alpha\d] to v3.
Args:
envoy_internal_shadow: generate a shadow for Envoy internal use containing deprecated fields.
file_proto: v2[alpha\d] FileDescriptorProto message.
Returns:
v3 FileDescriptorProto message.
"""
# Load type database.
typedb = utils.GetTypeDb()
# If this isn't a proto in an upgraded package, return None.
if file_proto.name not in typedb.next_version_protos or not typedb.next_version_protos[
file_proto.name]:
return None
# Otherwise, this .proto needs upgrading, do it.
return traverse.TraverseFile(file_proto, UpgradeVisitor(typedb, envoy_internal_shadow))
| {
"repo_name": "jrajahalme/envoy",
"path": "tools/protoxform/migrate.py",
"copies": "3",
"size": "10627",
"license": "apache-2.0",
"hash": 6613400925035987000,
"line_mean": 41.3386454183,
"line_max": 112,
"alpha_frac": 0.6876823186,
"autogenerated": false,
"ratio": 3.6121685927940175,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5799850911394018,
"avg_score": null,
"num_lines": null
} |
"""api URL Configuration
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^auth/', include('rest_framework_social_oauth2.urls')),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^', include('iitkgp.urls')),
url(r'^', include('mining.urls')),
url(r'^', include('menu.urls')),
url(r'^', include('bell.urls')),
url(r'^', include('city.urls')),
url(r'^', include('Token.urls')),
]
urlpatterns += staticfiles_urlpatterns() | {
"repo_name": "dominicneeraj/Technex_api",
"path": "api/urls.py",
"copies": "1",
"size": "1321",
"license": "mit",
"hash": -4594076713696050000,
"line_mean": 37.8823529412,
"line_max": 77,
"alpha_frac": 0.6858440575,
"autogenerated": false,
"ratio": 3.5510752688172045,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47369193263172044,
"avg_score": null,
"num_lines": null
} |
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import (url, include)
from django.contrib import admin
from rest_framework_swagger.views import get_swagger_view
from rest_framework.routers import DefaultRouter
from citizens.views import CitizenViewSet
# API REST views
api_routes = DefaultRouter()
api_routes.register(r'citizen', CitizenViewSet)
# Documentation views
schema_view = get_swagger_view()
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(api_routes.urls)),
url(r'^docs/', schema_view),
]
| {
"repo_name": "jaconsta/soat_cnpx",
"path": "api/api/urls.py",
"copies": "1",
"size": "1154",
"license": "mit",
"hash": 7905527873555374000,
"line_mean": 31.9714285714,
"line_max": 79,
"alpha_frac": 0.7183708839,
"autogenerated": false,
"ratio": 3.4142011834319526,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46325720673319526,
"avg_score": null,
"num_lines": null
} |
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from .settings.base import BASE_URL
# fix site url for admins
admin.site.site_url = f'/{BASE_URL}'
appUrlPatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('api.urls')),
]
# serve app urls under baseUrl
urlpatterns = [
url(r'^{0}'.format(BASE_URL), include(appUrlPatterns))
]
| {
"repo_name": "micnigh/django-react-todo-app",
"path": "api/project/urls.py",
"copies": "1",
"size": "1119",
"license": "mit",
"hash": 307737744846847500,
"line_mean": 32.9090909091,
"line_max": 79,
"alpha_frac": 0.7068811439,
"autogenerated": false,
"ratio": 3.4220183486238533,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9628899492523852,
"avg_score": 0,
"num_lines": 33
} |
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
url(r'^accounts/', include('registration.urls')),
url(r'^captcha/', include('captcha_service.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^upload/complete', TemplateView.as_view(template_name='upload_complete.html'), name='upload_complete'),
url(r'^upload/', TemplateView.as_view(template_name='upload.html'), name='upload'),
url(r'^download/', TemplateView.as_view(template_name='download.html'),
name='download'),
]
| {
"repo_name": "HPI-DeepLearning/CaptchaService",
"path": "server/api/urls.py",
"copies": "1",
"size": "1350",
"license": "mit",
"hash": 8601334276148616000,
"line_mean": 44,
"line_max": 113,
"alpha_frac": 0.7,
"autogenerated": false,
"ratio": 3.5340314136125652,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9730675485914533,
"avg_score": 0.0006711855396065922,
"num_lines": 30
} |
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from django.contrib import admin
# from client.views import ClientViewSet
#
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
# router.register(r'clients', ClientViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# client
url(r'', include('client.urls')),
# document
url(r'', include('document.urls')),
#apilogin
url(r'', include('apiauth.urls')),
url(r'^admin/', admin.site.urls),
] | {
"repo_name": "apiaas/drawer-api",
"path": "api/urls.py",
"copies": "1",
"size": "1453",
"license": "apache-2.0",
"hash": 7720042213109682000,
"line_mean": 35.35,
"line_max": 83,
"alpha_frac": 0.7068134893,
"autogenerated": false,
"ratio": 3.678481012658228,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4885294501958228,
"avg_score": null,
"num_lines": null
} |
API_URL = "http://q.daskeyboard.com"
headers = {'Content-Type': 'application/json'}
data = {
"clientId": "",
"clientSecret": "",
"grantType": "client_credentials"
}
# result = requests.post(API_URL + "/oauth/1.3/token", json=data, headers=headers)
# access_token = result.json()["access_token"]
from pprint import pprint
from random import choice
from universalclient import Client
q_api = Client(API_URL, headers=headers)
response = q_api.oauth._("1.3").token.post(json=data)
json_data = response.json()
pprint(json_data)
access_token = json_data["access_token"]
zones = q_api.api._("1.0").DK5QPID.zones.get(headers={"Authorization": "Bearer " + access_token})
signals = q_api.api._("1.0").signals._setArgs(headers={"Authorization": "Bearer " + access_token})
def gen_hex_colour_code():
return ''.join([choice('0123456789ABCDEF') for _ in xrange(6)])
for k in zones.json():
signal_data = {
"name": "all of them at once",
"pid": "DK5QPID",
"effect": "SET_COLOR",
"zoneId": k["id"],
"color": "#FFF"
}
print "setting '%s'" % k["name"]
response = signals.post(json=signal_data)
if not response.ok:
pprint(response.json())
| {
"repo_name": "bertrandvidal/stuff",
"path": "5q/py5q.py",
"copies": "1",
"size": "1214",
"license": "unlicense",
"hash": -2259019662857294000,
"line_mean": 26.5909090909,
"line_max": 98,
"alpha_frac": 0.6326194399,
"autogenerated": false,
"ratio": 3.145077720207254,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.926203263851643,
"avg_score": 0.0031329043181648406,
"num_lines": 44
} |
api_url = "https://api.robinhood.com"
def login():
return api_url + "/oauth2/token/"
def logout():
return api_url + "/oauth2/revoke_token/"
def investment_profile():
return api_url + "/user/investment_profile/"
def accounts():
return api_url + "/accounts/"
def ach(option):
'''
Combination of 3 ACH endpoints. Options include:
* iav
* relationships
* transfers
'''
return api_url + "/ach/iav/auth/" if option == "iav" else api_url + "/ach/{_option}/".format(_option=option)
def applications():
return api_url + "/applications/"
def dividends():
return api_url + "/dividends/"
def edocuments():
return api_url + "/documents/"
def instruments(instrumentId=None, option=None):
'''
Return information about a specific instrument by providing its instrument id.
Add extra options for additional information such as "popularity"
'''
return api_url + "/instruments/" + ("{id}/".format(id=instrumentId) if instrumentId else "") + ("{_option}/".format(_option=option) if option else "")
def margin_upgrades():
return api_url + "/margin/upgrades/"
def markets():
return api_url + "/markets/"
def notifications():
return api_url + "/notifications/"
def orders(orderId=None):
return api_url + "/orders/" + ("{id}/".format(id=orderId) if orderId else "")
def password_reset():
return api_url + "/password_reset/request/"
def portfolios():
return api_url + "/portfolios/"
def positions():
return api_url + "/positions/"
def quotes():
return api_url + "/quotes/"
def historicals():
return api_url + "/quotes/historicals/"
def document_requests():
return api_url + "/upload/document_requests/"
def user():
return api_url + "/user/"
def watchlists():
return api_url + "/watchlists/"
def news(stock):
return api_url + "/midlands/news/{_stock}/".format(_stock=stock)
def fundamentals(stock):
return api_url + "/fundamentals/{_stock}/".format(_stock=stock)
def tags(tag=None):
'''
Returns endpoint with tag concatenated.
'''
return api_url + "/midlands/tags/tag/{_tag}/".format(_tag=tag)
def chain(instrumentid):
return api_url + "/options/chains/?equity_instrument_ids={_instrumentid}".format(_instrumentid=instrumentid)
def options(chainid, dates, option_type):
return api_url + "/options/instruments/?chain_id={_chainid}&expiration_dates={_dates}&state=active&tradability=tradable&type={_type}".format(_chainid=chainid, _dates=dates, _type=option_type)
def market_data(optionid):
return api_url + "/marketdata/options/{_optionid}/".format(_optionid=optionid)
def convert_token():
return api_url + "/oauth2/migrate_token/"
| {
"repo_name": "MeheLLC/Robinhood",
"path": "Robinhood/endpoints.py",
"copies": "1",
"size": "2709",
"license": "mit",
"hash": 4033072038718945300,
"line_mean": 26.6428571429,
"line_max": 195,
"alpha_frac": 0.661498708,
"autogenerated": false,
"ratio": 3.3444444444444446,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45059431524444443,
"avg_score": null,
"num_lines": null
} |
API_URL = 'https://www.tsd-aff.com/cgi-bin/xml_core.exe'
EXT_START_SESSION_URL = 'https://www.tsd-aff.com/cgi-bin/xml_start_session.exe'
DATE_SLUG_MAP = (
{
'slug': 'today',
'auto_date': 'today_only',
},
{
'slug': 'this-week',
'auto_date': 'next_week',
}
)
AUTO_DATE_RANGE = (
'today_only', 'this_weekend', 'next_week',
'this_month', 'next_month',
)
NO_TIME_DESCR = 'Select'
DEFAULT_CONCESSION_DESCR = 'Standard'
SMALL_IMAGE = 'square'
MEDIUM_IMAGE = 'landscape'
LARGE_IMAGE = 'triplet_one'
LARGE_IMAGE_TWO = 'triplet_two'
LARGE_IMAGE_THREE = 'triplet_three'
LARGE_IMAGE_FOUR = 'triplet_four'
LARGE_IMAGE_FIVE = 'triplet_five'
MARQUEE_IMAGE = 'marquee'
SEATING_IMAGE = 'seating_plan'
SUPPLIER_IMAGE = 'supplier'
REQUEST_MEDIA = [
SMALL_IMAGE, MEDIUM_IMAGE, LARGE_IMAGE, LARGE_IMAGE_TWO,
LARGE_IMAGE_THREE, LARGE_IMAGE_FOUR, LARGE_IMAGE_FIVE,
MARQUEE_IMAGE, SEATING_IMAGE, SUPPLIER_IMAGE,
]
LARGE_IMAGE_LIST = [
LARGE_IMAGE, LARGE_IMAGE_TWO, LARGE_IMAGE_THREE,
LARGE_IMAGE_FOUR, LARGE_IMAGE_FIVE,
]
# timeout in seconds for API requests
API_REQUEST_TIMEOUT = 120
| {
"repo_name": "graingert/pyticketswitch",
"path": "pyticketswitch/settings.py",
"copies": "2",
"size": "1146",
"license": "mit",
"hash": -8533405353884759000,
"line_mean": 23.3829787234,
"line_max": 79,
"alpha_frac": 0.6579406632,
"autogenerated": false,
"ratio": 2.5076586433260393,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41655993065260394,
"avg_score": null,
"num_lines": null
} |
"""API urls for password recovery
"""
from pulsar.api import MethodNotAllowed
from lux.core import AuthenticationError
from lux.models import Schema, fields, ValidationError
from lux.ext.rest import RestRouter, route
from .registrations import (
RegistrationModel, PasswordSchema, RegistrationSchema
)
from . import ensure_service_user
from ..models import RegistrationType
class ChangePasswordRequestSchema(Schema):
email = fields.Email(required=True)
def post_load(self, data):
user = self.get_user(data.request, data['email'])
return self.create_model(data.session, user, RegistrationType.password)
def get_user(self, request, email):
raise ValidationError("Can't find user, sorry")
class ChangePasswordSchema(PasswordSchema):
old_password = fields.Password(required=True)
def clean_old_password(self, value):
request = self.request
user = request.cache.user
auth_backend = request.cache.auth_backend
try:
if user.is_authenticated():
auth_backend.authenticate(request, user=user, password=value)
else:
raise AuthenticationError('not authenticated')
except AuthenticationError as exc:
raise fields.ValidationError(str(exc))
return value
class PasswordResetModel(RegistrationModel):
def get_instance(self, request, **kw):
ensure_service_user(request, MethodNotAllowed)
return super().get_instance(request, **kw)
def update_registration(self, request, reg, data, session=None):
backend = request.cache.auth_backend
password = data['password']
with self.session(request, session=session) as session:
user = reg.user
user.password = backend.password(request, password)
session.add(user)
session.delete(reg)
return {'success': True}
class PasswordsCRUD(RestRouter):
"""
---
summary: Endpoints for password recovery
tags:
- authentication
- password
"""
model = PasswordResetModel('passwords', RegistrationSchema, type=2)
@route(default_response=201,
default_response_schema=RegistrationSchema,
body_schema=ChangePasswordRequestSchema)
def post(self, request):
"""
---
summary: Request a new password-reset
responses:
201:
description: A new password-reset request was
successfully created
"""
ensure_service_user(request)
return self.model.create_response(request)
@route('<id>/change',
default_response=204,
body_schema=ChangePasswordSchema,
responses=(400, 401, 403, 404, 422))
def post_change(self, request):
"""
---
summary: Change a password for a user
description: given a password-reset change id,
change the user password
responses:
204:
description: Password change was successful
"""
return self.model.confirm_response(request)
| {
"repo_name": "quantmind/lux",
"path": "lux/ext/auth/rest/passwords.py",
"copies": "1",
"size": "3131",
"license": "bsd-3-clause",
"hash": 1145919485363786000,
"line_mean": 30.31,
"line_max": 79,
"alpha_frac": 0.6416480358,
"autogenerated": false,
"ratio": 4.584187408491947,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5725835444291947,
"avg_score": null,
"num_lines": null
} |
#API Usage Example
#==========
#To use: Modify the fqdn, username, and password
import isilon
import time
import logging
def main():
fqdn = '192.168.167.101' #change to your cluster
username = 'root'
password = 'a'
#httplib.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.CRITICAL)
logging.captureWarnings(True)
#connect, secure=False allows us to bypass the CA validation
api = isilon.API(fqdn, username, password, secure=False)
# not necessary as it will connect automatically on auth failure
# but this avoids the initial attempt failure
print("Connecting")
api.session.connect()
#Check for old bad snaps and delete
print("Checking for older snaps")
if api.platform.snapshot('testsnap') :
print("We found an existing testsnap, let's delete that...")
api.platform.snapshot_delete('testsnap')
#This shows how we can pass params directly to the API though specifically not called
#out as a param for the snapshot_create function.
print("create a snapshot on %s, to expire in 60 seconds" % testfolder )
api.platform.snapshot_create("testsnap",testfolder,expires=int(time.time()+60))
print("confirm test snapshot was created details:")
print(api.platform.snapshot('testsnap'))
print("Modify the snapshot expire time and rename to testsnap2")
api.platform.snapshot_modify('testsnap',name='testsnap2',expires=int(time.time() + 120))
print("Rename back testsnap")
api.platform.snapshot_modify('testsnap2',name='testsnap')
#debug last API call:
api.session.debug_last()
#list all snaps
print('\nListing of All Snaps:')
for snap in api.platform.snapshot(limit=2):
print("Name: %s, Path: %s, Created: %s" % (snap['name'], snap['path'], time.ctime(snap['created']) ))
#cleanup our testnsap
api.platform.snapshot_delete('testsnap')
print("list all quotas")
for q in api.platform.quota():
pcnt_used = 100 * q['usage']['logical'] / q['thresholds']['hard']
print("Path %s Persona: %s Percent Used: %s" % (q['path'] , q['persona'], pcnt_used))
if __name__ == "__main__":
main() | {
"repo_name": "sile16/python-isilon-api",
"path": "api_example.py",
"copies": "2",
"size": "2181",
"license": "mit",
"hash": 2339419487736192000,
"line_mean": 27.904109589,
"line_max": 103,
"alpha_frac": 0.6795048143,
"autogenerated": false,
"ratio": 3.4024960998439937,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5082000914143994,
"avg_score": null,
"num_lines": null
} |
"""API utility functions.
Version Added:
3.0
"""
from __future__ import unicode_literals
from rbtools.api.client import RBClient
from reviewbot import get_version_string
from reviewbot.config import config
def get_api_root(url, username=None, api_token=None, session=None):
"""Return the root of the Review Board API.
Either ``session`` or both ``username`` and ``api_token`` must be
provided.
Args:
url (unicode):
The path to the Review Board server.
username (unicode, optional):
The username used for authentication.
api_token (unicode, optional):
The API token used for authentication.
session (unicode, optional):
An existing Review Board session identifier.
Returns:
rbtools.api.resources.RootResource:
The root API resource for the server.
Raises:
rbtools.api.errors.APIError:
There was an error fetching the root resource.
"""
client = RBClient(url,
agent='ReviewBot/%s' % get_version_string(),
cookie_file=config['cookie_path'],
username=username,
api_token=api_token,
session=session)
return client.get_root()
| {
"repo_name": "reviewboard/ReviewBot",
"path": "bot/reviewbot/utils/api.py",
"copies": "1",
"size": "1300",
"license": "mit",
"hash": 6148282321621236000,
"line_mean": 25.5306122449,
"line_max": 69,
"alpha_frac": 0.6053846154,
"autogenerated": false,
"ratio": 4.436860068259386,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5542244683659386,
"avg_score": null,
"num_lines": null
} |
"""ApiUtil.py - Utilities for RESTful APIs"""
from flask import current_app
# Base messages, allowing for future localization of API error messages
API_REQUIRES_JSON = 'All PUT/POST API requests require JSON, and this request did not'
API_REQUIRES_FIELDS = 'Must provide {} for this API'
API_CREATE_EXISTS = '{} with {} already exists, create ignored'
API_OBJECT_NOT_FOUND = '{} failed because {} with {} not found'
API_SCHEMA_ERRORS = '{} failed {} due to errors: {}'
API_RECAPTCHA_FAILS = 'ReCaptcha check failed'
API_SUCCESS = '{} {} successfully'
API_FACEBOOK_PROFILE = 'Unable to get required Facebook profile elements'
def api_message(api_method, message, code, obj_id=None):
"""Creates and debug logs API response when a payload is not required"""
# Set success component of return based on code
success = True
if code >= 400:
success = False
resp = {
'success': success,
'msg': message,
}
if obj_id:
resp['id'] = obj_id
current_app.logger.debug('API %s returning %s with status %d and id %d',
api_method, message, code, obj_id)
else:
current_app.logger.debug('API %s returning %s with status %d',
api_method, message, code)
return resp, code
def validate_json_contains(api_method, request, fields, code=400):
"""Validates that a request contains JSON with specific fields"""
json = request.get_json()
# If the required fields are not in the json, return none and error payload
for field in fields:
if not field in json:
return None, api_message(api_method, API_REQUIRES_FIELDS.format(fields), code)
# If all required fields are present, return the json with no error message
return json, None
def wrap_with_links(obj, links, val, root_path, many=False):
"""Adds links key to object (first argument) based on links dictionary and value"""
if many:
for item in obj:
item['links'] = {}
for key in links:
item['links'][key] = root_path + links[key].format(item[val])
else:
obj['links'] = {}
for key in links:
obj['links'][key] = root_path + links[key].format(obj[val])
return obj
| {
"repo_name": "Wittle-South-LLC/base",
"path": "server/src/APIs/ApiUtil.py",
"copies": "1",
"size": "2275",
"license": "mit",
"hash": 1907345172425065200,
"line_mean": 40.3636363636,
"line_max": 90,
"alpha_frac": 0.6338461538,
"autogenerated": false,
"ratio": 3.888888888888889,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5022735042688888,
"avg_score": null,
"num_lines": null
} |
""" API v0 URLs. """
from django.conf.urls import url
from django.urls import path
from .views import (
EchoDataView,
ResponseViewSet,
ErrorViewSet,
GenReportView,
CourseReportViewSet,
HealthCheck,
OnboardingStatus,
OnboardingBpAnalysis,
BestPracticeCreate,
BestPracticeUpload,
UnitViewSet,
)
app_name = 'v0'
urlpatterns = [
url(
r'^courses/(?P<course_id>\d+)/responses/$',
ResponseViewSet.as_view({'get': 'list'}),
name='responses'
),
url(
r'^courses/(?P<course_id>\d+)/errors/$',
ErrorViewSet.as_view({'get': 'list'}),
name='errors'
),
url(
r'^courses/(?P<course_id>\d+)/reports/$',
CourseReportViewSet.as_view({'get': 'list'}),
name='reports'
),
url(
r'^gen-report/$',
GenReportView.as_view(),
name='gen-report'
),
url(
r'^echo/data/$',
EchoDataView.as_view(),
name='echo-data',
),
url(r'^health/*$', HealthCheck.as_view(), name='health-check'),
url(r'^onboarding-status/$', OnboardingStatus.as_view(), name='onboarding-status'),
url(r'^bp-analysis/$', OnboardingBpAnalysis.as_view(), name='onboarding_bp2-analysis'),
path('bp/create/', BestPracticeCreate.as_view(), name='bp-creation'),
path('bp/upload/', BestPracticeUpload.as_view(), name='bp-upload'),
path('unit/update/<int:pk>/', UnitViewSet.as_view({'put': 'update', 'get': 'retrieve'}), name='unit_update')
]
| {
"repo_name": "cjlee112/socraticqs2",
"path": "mysite/api/v0/urls.py",
"copies": "1",
"size": "1505",
"license": "apache-2.0",
"hash": -3960347761718940000,
"line_mean": 25.4035087719,
"line_max": 112,
"alpha_frac": 0.5900332226,
"autogenerated": false,
"ratio": 3.351893095768374,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.9439199760552308,
"avg_score": 0.0005453115632131853,
"num_lines": 57
} |
# /api/v1/dataresource/
# auth
# url(r'^new/', views.create_dataset),
# url(r'^(?P<slug>[a-z0-9\-/]+)/schema/', views.schema),
# url(r'^(?P<slug>[a-z0-9\-/]+)/query/(?P<x1>[0-9\-.]+),(?P<y1>[0-9\-.]+),(?P<x2>[0-9\-.]+),(?P<y2>[0-9\-.]+)/',
# views.query),
# url(r'^(?P<slug>[a-z0-9\-/]+)/query/', views.query),
# url(r'^(?P<slug>[a-z0-9\-/]+)/add_column/', views.add_column),
# url(r'^(?P<slug>[a-z0-9\-/]+)/(?P<ogc_fid>[0-9]+)/', views.CRUDView.as_view()),
# url(r'^(?P<slug>[a-z0-9\-/]+)/(?P<ogc_fid_start>[0-9]+):(?P<ogc_fid_end>[0-9]+)/', views.CRUDView.as_view()),
# url(r'^(?P<slug>[a-z0-9\-/]+)/(?P<ogc_fid_start>[0-9]+),(?P<limit>[0-9]+)/', views.CRUDView.as_view()),
# url(r'^(?P<slug>[a-z0-9\-/]+)/fork/', views.derive_dataset),
# url(r'^(?P<slug>[a-z0-9\-/]+)/fork_geometry/', views.create_dataset_with_parent_geometry),
# url(r'^(?P<slug>[a-z0-9\-/]+)/', views.CRUDView.as_view()),
import json
from unittest import TestCase
import requests
AK = '1c6a41ed6a5bc199d10e9594090b17cb83213dbb' # API_KEY
host = 'http://localhost:8000/'
# @skip
class TestRestAPI(TestCase):
def assertSuccess(self, response, msg='response status code: {code}\n{response}'):
msg = msg.format(code=response.status_code, response=response.text)
self.assertGreaterEqual(response.status_code, 200, msg=msg)
self.assertLess(response.status_code, 300, msg=msg)
def test_create_dataset(self):
blank_dataset = requests.get(
host + 'ga_resources/new/',
headers={
"content-type" : 'application/json'
},
params={
"api_key" : AK,
"title" : 'test create empty dataset'
}
)
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/', params={
"api_key": AK,
"title": 'test create empty dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns)
self.assertSuccess(blank_dataset)
self.assertIn(
'path', blank_dataset.json(),
msg='no path in response: {response}'.format(response=blank_dataset.text))
self.assertIn(
'path', blank_dataset_with_columns.json(),
msg='no path in response: {response}'.format(response=blank_dataset_with_columns.text))
def test_fork_dataset(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test create empty dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns)
self.assertIn(
'path', blank_dataset_with_columns.json(),
msg='no path in response: {response}'.format(response=blank_dataset_with_columns.text))
path = blank_dataset_with_columns.json()['path']
new_dataset = requests.get(host + 'ga_resources/' + path + '/fork/',
headers={
"content-type": 'application/json'
}
, params={
"api_key" : AK,
})
self.assertSuccess(new_dataset, msg='failed to fork dataset')
def test_fork_dataset_geometry(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test create empty dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns)
self.assertIn(
'path', blank_dataset_with_columns.json(),
msg='no path in response: {response}'.format(response=blank_dataset_with_columns.text))
path = blank_dataset_with_columns.json()['path']
new_dataset = requests.get(host + 'ga_resources/' + path + '/fork_geometry/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
})
self.assertSuccess(new_dataset)
def test_schema(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
schema = requests.get(host + 'ga_resources/{path}/schema/'.format(path=path))
self.assertSuccess(schema)
schema = schema.json()
self.assertListEqual(
sorted([c['name'].lower() for c in schema]),
['geometry','i','j','name','ogc_fid'],
msg='schema should have had 5 fields, was\n{schema}'.format(schema=schema))
def test_add_column(self):
blank_dataset = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test create empty dataset'
})
self.assertSuccess(blank_dataset, msg='failed to create dataset {code}')
path = blank_dataset.json()['path']
add_column = requests.get(host + 'ga_resources/' + path + '/add_column/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"name" : "p",
"type" : "text"
})
self.assertSuccess(add_column)
def test_add_row(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
def test_attribute_query(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.get(host + 'ga_resources/' + path + '/query/',
headers={
"content-type": 'application/json'
}
, params={
"name__contains" : 'oll'
})
self.assertSuccess(query)
self.assertGreater(len(query.json()), 0, msg='zero results returned')
def test_spatial_query(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.get(host + 'ga_resources/' + path + '/query/0,0,2,2/')
self.assertSuccess(query)
self.assertGreater(len(query.json()), 0, msg='zero results returned')
query = requests.get(host + 'ga_resources/' + path + '/query/',
headers={
"content-type": 'application/json'
}
, params={
"g" : "POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))"
})
self.assertSuccess(query)
self.assertGreater(len(query.json()), 0, msg='zero results returned')
def test_get_row(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.get(host + 'ga_resources/' + path + '/1/')
self.assertSuccess(query)
self.assertGreater(len(query.json().keys()), 0, msg='no results returned')
def test_get_rows(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(0 1)"
})
self.assertSuccess(add_row)
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(2 1)"
})
self.assertSuccess(add_row)
query = requests.get(host + 'ga_resources/' + path + '/1:3/',
headers={
"content-type": 'application/json'
}
)
self.assertSuccess(query)
self.assertEqual(len(query.json()), 3, msg='no results returned {n}'.format(n=len(query.json())))
query = requests.get(host + 'ga_resources/' + path + '/1,3/',
headers={
"content-type": 'application/json'
}
)
self.assertSuccess(query)
self.assertEqual(len(query.json()), 3, msg='no results returned {n}'.format(n=len(query.json())))
query = requests.get(host + 'ga_resources/' + path + '/0,3/',
headers={
"content-type": 'application/json'
}
)
self.assertSuccess(query)
self.assertEqual(len(query.json()), 3, msg='no results returned {n}'.format(n=len(query.json())))
def test_only(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.get(host + 'ga_resources/' + path + '/1/')
self.assertSuccess(query)
self.assertGreater(len(query.json().keys()), 0, msg='no results returned')
def test_update_row(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.put(host + 'ga_resources/' + path + '/1/',
headers={
"content-type": 'application/json'
}
, params={
"api_key":AK,
"i" : 1.0
})
self.assertSuccess(query)
def test_delete_row(self):
blank_dataset_with_columns = requests.get(host + 'ga_resources/new/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"title": 'test schema dataset',
'srid': 4326,
'columns_definitions': json.dumps({
"i": "real",
"j": "integer",
"name": "text"
})
})
self.assertSuccess(blank_dataset_with_columns, msg='failed to create dataset {code}')
path = blank_dataset_with_columns.json()['path']
add_row = requests.post(host + 'ga_resources/' + path + '/',
headers={
"content-type": 'application/json'
}
, params={
"api_key": AK,
"i": 0.0,
"j": 2,
"name": "folly",
'GEOMETRY': "POINT(1 1)"
})
self.assertSuccess(add_row)
query = requests.delete(host + 'ga_resources/' + path + '/1/',
headers={
"content-type": 'application/json'
},
params={ "api_key": AK, }
)
self.assertSuccess(query) | {
"repo_name": "hydroshare/hydroshare_temp",
"path": "ga_resources/tests/http_tests.py",
"copies": "2",
"size": "20491",
"license": "bsd-3-clause",
"hash": -5066294926264110000,
"line_mean": 37.0892193309,
"line_max": 112,
"alpha_frac": 0.4114489288,
"autogenerated": false,
"ratio": 4.4808659523288865,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5892314881128886,
"avg_score": null,
"num_lines": null
} |
# API v1
import logging
from django.conf import settings
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import FormView
from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasScope
from rest_framework import mixins, status, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.authentication.models import Email
from apps.authentication.models import OnlineUser as User
from apps.inventory.models import Item
from apps.payment.models import PaymentTransaction
from apps.shop.forms import SetRFIDForm
from apps.shop.models import MagicToken, OrderLine
from apps.shop.serializers import (ItemSerializer, OrderLineSerializer, TransactionSerializer,
UserOrderLineSerializer, UserSerializer)
from apps.shop.utils import create_magic_token
class OrderLineViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
queryset = OrderLine.objects.all()
serializer_class = OrderLineSerializer
authentication_classes = [OAuth2Authentication]
permission_classes = [TokenHasScope]
required_scopes = ['shop.readwrite']
def create(self, request):
serializer = OrderLineSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
def perform_create(self, serializer):
serializer.save()
class TransactionViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
queryset = PaymentTransaction.objects.all()
serializer_class = TransactionSerializer
authentication_classes = [OAuth2Authentication]
permission_classes = [TokenHasScope]
required_scopes = ['shop.readwrite']
def create(self, request):
serializer = TransactionSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
def perform_create(self, serializer):
serializer.save()
class UserOrderViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin):
serializer_class = UserOrderLineSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
return OrderLine.objects.filter(user=self.request.user)
class UserViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin, APIView):
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = [OAuth2Authentication]
permission_classes = [TokenHasScope]
required_scopes = ['shop.readwrite']
filter_fields = ('rfid',)
class InventoryViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
queryset = Item.objects.filter(available=True).order_by('pk')
serializer_class = ItemSerializer
permission_classes = (AllowAny,)
pagination_class = None
class SetRFIDView(APIView):
authentication_classes = [OAuth2Authentication]
permission_classes = [TokenHasScope]
required_scopes = ['shop.readwrite']
def post(self, request):
username = request.data.get("username", '').lower()
password = request.data.get("password", '')
request_magic_link = request.data.get('magic_link', False)
send_magic_link_email = request.data.get('send_email', True)
if not username:
return Response('Missing authentication details', status=status.HTTP_400_BAD_REQUEST)
if '@' in username:
email = Email.objects.filter(email=username)
if email:
username = email[0].user.username
user = auth.authenticate(username=username, password=password)
rfid = request.data.get("rfid", '')
if not rfid:
return Response('Missing RFID from request payload', status=status.HTTP_400_BAD_REQUEST)
if user and rfid:
if user.rfid == rfid:
return Response("OK", status=status.HTTP_200_OK)
user.rfid = rfid
user.save()
return Response("OK", status=status.HTTP_200_OK)
if not user and username and rfid and request_magic_link:
onlineuser = None
try:
onlineuser = User.objects.get(username=username)
except User.DoesNotExist:
return Response('User does not exist', status=status.HTTP_400_BAD_REQUEST)
magic_token = create_magic_token(onlineuser, rfid, send_token_by_email=send_magic_link_email)
data = {
'token': str(magic_token.token),
'url': '{}{}'.format(settings.BASE_URL, reverse('shop_set_rfid', args=[str(magic_token.token)]))
}
return Response(data=data, status=status.HTTP_201_CREATED)
return Response("Invalid user credentials", status=status.HTTP_400_BAD_REQUEST)
@method_decorator(login_required, name='dispatch')
class SetRFIDWebView(FormView):
form_class = SetRFIDForm
template_name = 'shop/set_rfid.html'
success_url = reverse_lazy('home')
def get(self, request, token='', *args, **kwargs):
get_object_or_404(MagicToken, token=token)
return super().get(request, token, *args, **kwargs)
def get_context_data(self, **kwargs):
kwargs['current_rfid'] = self.request.user.rfid
kwargs['token'] = self.kwargs.get('token')
return super().get_context_data(**kwargs)
def get_initial(self):
initial = super().get_initial()
initial['rfid'] = MagicToken.objects.get(token=self.kwargs.get('token')).data
return initial
def post(self, request, token='', *args, **kwargs):
logger = logging.getLogger(__name__)
form = self.get_form()
if not form.is_valid():
return self.form_invalid(form)
if not token:
form.add_error('Det finnes ingen token i denne forespørselen.')
return self.form_invalid(form)
magictoken = None
try:
magictoken = MagicToken.objects.get(token=token)
except MagicToken.DoesNotExist:
form.add_error('Tokenet du prøver å bruke eksisterer ikke.')
return self.form_invalid(form)
old_rfid = magictoken.user.rfid
magictoken.user.rfid = magictoken.data
magictoken.user.save()
logger.debug('{authed_user} updated RFID for {user} (from "{old}" to "{new}").'.format(
authed_user=self.request.user, user=magictoken.user,
old=old_rfid, new=magictoken.data
))
magictoken.delete()
messages.success(request, 'Oppdaterte RFID for {}'.format(magictoken.user))
return self.form_valid(form)
| {
"repo_name": "dotKom/onlineweb4",
"path": "apps/shop/views.py",
"copies": "1",
"size": "7097",
"license": "mit",
"hash": 2935421780059293000,
"line_mean": 36.935828877,
"line_max": 112,
"alpha_frac": 0.6857908091,
"autogenerated": false,
"ratio": 4.0011280315848845,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5186918840684884,
"avg_score": null,
"num_lines": null
} |
"""API v1 routes for builds."""
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Tuple
from flask import jsonify, request
from flask_accept import accept_fallback
from keeper.api import api
from keeper.auth import permission_required, token_auth
from keeper.logutils import log_route
from keeper.models import Build, Permission, Product, db
from keeper.taskrunner import (
append_task_to_chain,
insert_task_url_in_response,
launch_task_chain,
mock_registry,
)
from keeper.tasks.dashboardbuild import build_dashboard
if TYPE_CHECKING:
from flask import Response
# Register imports of celery task chain launchers
mock_registry.extend(
[
"keeper.api.builds.launch_task_chain",
"keeper.api.builds.append_task_to_chain",
]
)
@api.route("/builds/<int:id>", methods=["PATCH"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.UPLOAD_BUILD)
def patch_build(id: int) -> Tuple[Response, int, Dict[str, str]]:
"""Mark a build as uploaded.
This method should be called when the documentation has been successfully
uploaded to the S3 bucket, setting the 'uploaded' field to ``True``.
**Authorization**
User must be authenticated and have ``upload_build`` permissions.
**Example request**
.. code-block:: http
PATCH /builds/1 HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKcFlYUWlPakUwTlRZM056SXpORGdzSW1WNGNDSTZNVFEx...
Connection: keep-alive
Content-Length: 18
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/0.9.3
{
"uploaded": true
}
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:28 GMT
Location: http://localhost:5000/builds/1
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param id: ID of the build.
:<json bool uploaded: True if the built documentation has been uploaded
to the S3 bucket.
:resheader Location: URL of the created build.
:statuscode 200: No error.
:statuscode 404: Build not found.
"""
build = Build.query.get_or_404(id)
try:
build.patch_data(request.json)
build_url = build.get_url()
db.session.commit()
# Run the task queue
append_task_to_chain(build_dashboard.si(build.product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
except Exception:
db.session.rollback()
raise
return jsonify(response), 200, {"Location": build_url}
@api.route("/builds/<int:id>", methods=["DELETE"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.DEPRECATE_BUILD)
def deprecate_build(id: int) -> Tuple[Response, int]:
"""Mark a build as deprecated.
**Authorization**
User must be authenticated and have ``deprecate_build`` permissions.
**Example request**
.. code-block:: http
DELETE /builds/1 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKcFlYUWlPakUwTlRZM056SXpORGdzSW1WNGNDSTZNVFEx...
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
User-Agent: HTTPie/0.9.3
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:29 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param id: ID of the build.
:statuscode 200: No error.
:statuscode 404: Build not found.
"""
build = Build.query.get_or_404(id)
build.deprecate_build()
db.session.commit()
return jsonify({}), 200
@api.route("/products/<slug>/builds/", methods=["GET"])
@accept_fallback
@log_route()
def get_product_builds(slug: str) -> Response:
"""List all builds for a product.
**Example request**
.. code-block:: http
GET /products/lsst_apps/builds/ HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 96
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:28 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"builds": [
"http://localhost:5000/builds/1",
"http://localhost:5000/builds/2"
]
}
:param slug: Slug of the Product.
:>json array builds: List of URLs of Build entities for this product.
:statuscode 200: No error.
:statuscode 404: Product not found.
"""
build_urls = [
build.get_url()
for build in Build.query.join(Product, Product.id == Build.product_id)
.filter(Product.slug == slug)
.filter(Build.date_ended == None) # noqa: E711
.all()
]
return jsonify({"builds": build_urls})
@api.route("/builds/<int:id>", methods=["GET"])
@accept_fallback
@log_route()
def get_build(id: int) -> Response:
"""Show metadata for a single build.
**Example request**
.. code-block:: http
GET /builds/1 HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 367
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:28 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"bucket_name": "an-s3-bucket",
"bucket_root_dir": "lsst_apps/builds/b1",
"date_created": "2016-03-01T10:21:27.583795Z",
"date_ended": null,
"git_refs": [
"master"
],
"github_requester": "jonathansick",
"product_url": "http://localhost:5000/products/lsst_apps",
"self_url": "http://localhost:5000/builds/1",
"slug": "b1",
"surrogate_key": "d290d35e579141e889e954a0b1f8b611",
"uploaded": true
}
:param id: ID of the Build.
:>json string bucket_name: Name of the S3 bucket hosting the built
documentation.
:>json string bucket_root_dir: Directory (path prefix) in the S3 bucket
where this documentation build is located.
:>json string date_created: UTC date time when the build was created.
:>json string date_ended: UTC date time when the build was deprecated;
will be ``null`` for builds that are *not deprecated*.
:>json array git_refs: Git ref array that describes the version of the
documentation being built. Typically this array will be a single
string, e.g. ``['master']`` but may be a list of several refs for
multi-package builds with ltd-mason.
:>json string github_requester: GitHub username handle of person
who triggered the build (null is not available).
:>json string slug: slug of build; URL-safe slug.
:>json string product_url: URL of parent product entity.
:>json string published_url: Full URL where this build is published to
the reader.
:>json string self_url: URL of this build entity.
:>json string surrogate_key: The surrogate key attached to the headers
of all files on S3 belonging to this build. This allows LTD Keeper
to notify Fastly when an Edition is being re-pointed to a new build.
The client is responsible for uploading files with this value as
the ``x-amz-meta-surrogate-key`` value.
:>json bool uploaded: True if the built documentation has been uploaded
to the S3 bucket. Use :http:patch:`/builds/(int:id)` to
set this to `True`.
:statuscode 200: No error.
:statuscode 404: Build not found.
"""
return jsonify(Build.query.get_or_404(id).export_data())
| {
"repo_name": "lsst-sqre/ltd-keeper",
"path": "keeper/api/builds.py",
"copies": "1",
"size": "8057",
"license": "mit",
"hash": -3218584869562538500,
"line_mean": 28.5128205128,
"line_max": 79,
"alpha_frac": 0.6368375326,
"autogenerated": false,
"ratio": 3.694176983035305,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9831014515635305,
"avg_score": 0,
"num_lines": 273
} |
"""API v1 routes for Editions."""
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Tuple
from flask import jsonify, request
from flask_accept import accept_fallback
from keeper.api import api
from keeper.auth import permission_required, token_auth
from keeper.logutils import log_route
from keeper.models import Edition, Permission, Product, db
from keeper.taskrunner import (
append_task_to_chain,
insert_task_url_in_response,
launch_task_chain,
mock_registry,
)
from keeper.tasks.dashboardbuild import build_dashboard
if TYPE_CHECKING:
from flask import Response
# Register imports of celery task chain launchers
mock_registry.extend(
[
"keeper.api.editions.launch_task_chain",
"keeper.api.editions.append_task_to_chain",
]
)
@api.route("/products/<slug>/editions/", methods=["POST"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_EDITION)
def new_edition(slug: str) -> Tuple[Response, int, Dict[str, str]]:
"""Create a new Edition for a Product.
**Authorization**
User must be authenticated and have ``admin_edition`` permissions.
**Example request**
.. code-block:: http
POST /products/lsst_apps/editions/ HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKcFlYUWlPakUwTlRZM056SXpORGdzSW1WNGNDSTZNVFEx...
Connection: keep-alive
Content-Length: 150
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/0.9.3
{
"build_url": "http://localhost:5000/builds/1",
"slug": "latest",
"title": "Latest",
"mode:": "git_refs",
"tracked_refs": [
"master"
]
}
**Example response**
.. code-block:: http
HTTP/1.0 201 CREATED
Content-Length: 2
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:29 GMT
Location: http://localhost:5000/editions/1
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param slug: Product slug.
:<json string build_url: URL of the build entity this Edition uses.
:<json string slug: URL-safe name for edition. Don't include this field
when using ``autoincrement: true``.
:<json string title: Human-readable name for edition.
:<json str mode: Tracking mode.
``git_refs``: track the Git ref specified by ``tracked_refs``.
``lsst_doc``: track LSST document version tags.
:<json array tracked_refs: Git ref(s) that describe the version of the
Product that this this Edition is intended to point to when using
the ``git_refs`` tracking mode.
:<json bool autoincrement: Instead of providing a ``slug``, the server
automatically assigns an integer slug that is one larger than
existing slug integers. Starts from ``1``.
:resheader Location: URL of the created Edition resource.
:statuscode 201: No errors.
:statuscode 404: Product not found.
"""
product = Product.query.filter_by(slug=slug).first_or_404()
edition = Edition(product=product)
try:
edition.import_data(request.json)
db.session.add(edition)
db.session.commit()
edition_url = edition.get_url()
# Run the task queue
append_task_to_chain(build_dashboard.si(product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
except Exception:
db.session.rollback()
raise
return jsonify(response), 201, {"Location": edition_url}
@api.route("/editions/<int:id>", methods=["DELETE"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_EDITION)
def deprecate_edition(id: int) -> Tuple[Response, int]:
"""Deprecate an Edition of a Product.
When an Edition is deprecated, the current time is added to the
Edition's ``date_ended`` field. Any Edition record with a non-``null``
``date_ended`` field will be garbage-collected by LTD Keeper (the
deletion does not occur immediately upon API request).
**Authorization**
User must be authenticated and have ``admin_edition`` permissions.
**Example request**
.. code-block:: http
DELETE /editions/1 HTTP/1.1
Authorization: Basic ZXlKcFlYUWlPakUwTlRZM056SXpORGdzSW1WNGNDSTZNVFEx...
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
User-Agent: HTTPie/0.9.3
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:30 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param id: Edition id.
:statuscode 200: No errors.
:statuscode 404: Edition not found.
"""
edition = Edition.query.get_or_404(id)
edition.deprecate()
db.session.commit()
append_task_to_chain(build_dashboard.si(edition.product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
return jsonify(response), 200
@api.route("/products/<slug>/editions/", methods=["GET"])
@accept_fallback
@log_route()
def get_product_editions(slug: str) -> Response:
"""List all editions published for a Product.
**Example request**
.. code-block:: http
GET /products/lsst_apps/editions/ HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 62
Content-Type: application/json
Date: Tue, 01 Mar 2016 18:50:19 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"editions": [
"http://localhost:5000/editions/1"
]
}
:param slug: Slug of the Product.
:>json array editions: List of URLs of Edition entities for this Product.
:statuscode 200: No errors.
:statuscode 404: Product not found.
"""
edition_urls = [
edition.get_url()
for edition in Edition.query.join(
Product, Product.id == Edition.product_id
)
.filter(Product.slug == slug)
.filter(Edition.date_ended == None) # noqa: E711
.all()
]
return jsonify({"editions": edition_urls})
@api.route("/editions/<int:id>", methods=["GET"])
@accept_fallback
@log_route()
def get_edition(id: int) -> Response:
"""Show metadata for an Edition.
**Example request**
.. code-block:: http
GET /editions/1 HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 413
Content-Type: application/json
Date: Tue, 01 Mar 2016 18:50:18 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"build_url": "http://localhost:5000/builds/1",
"date_created": "2016-03-01T11:50:18.196724Z",
"date_ended": null,
"date_rebuilt": "2016-03-01T11:50:18.196706Z",
"mode": "git_refs",
"product_url": "http://localhost:5000/products/lsst_apps",
"published_url": "pipelines.lsst.io",
"self_url": "http://localhost:5000/editions/1",
"slug": "latest",
"surrogate_key": "2a5f38f27e3c46258fd9b0e69afe54fd",
"title": "Development master",
"tracked_refs": [
"master"
]
}
:param id: ID of the Edition.
:>json string build_url: URL of the build entity this Edition uses.
:>json string date_created: UTC date time when the edition was created.
:>json string date_ended: UTC date time when the edition was deprecated;
will be ``null`` for editions that are *not deprecated*.
:>json string date_rebuilt: UTC date time when the edition last re-pointed
to a different build.
:>json str mode: Tracking mode.
``git_refs``: track the Git ref specified by ``tracked_refs``.
``lsst_doc``: track LSST document version tags.
:>json string product_url: URL of parent product entity.
:>json string published_url: Full URL where this edition is published.
:>json string self_url: URL of this Edition entity.
:>json string slug: URL-safe name for edition.
:>json string surrogate_key: Surrogate key that should be used in the
``x-amz-meta-surrogate-control`` header of any the edition's S3
objects to control Fastly caching.
:>json string title: Human-readable name for edition.
:>json string tracked_refs: Git ref that this Edition points to. For multi-
repository builds, this can be a comma-separated list of refs to use,
in order of priority.
:statuscode 200: No errors.
:statuscode 404: Edition not found.
"""
return jsonify(Edition.query.get_or_404(id).export_data())
@api.route("/editions/<int:id>", methods=["PATCH"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_EDITION)
def edit_edition(id: int) -> Response:
"""Edit an Edition.
This PATCH method allows you to specify a subset of JSON fields to replace
existing fields in the Edition resource. Not all fields in an Edition are
editable via the API. See the allowed JSON fields below.
Use :http:delete:`/editions/(int:id)` to deprecate an edition.
The full resource record is returned.
**Authorization**
User must be authenticated and have ``admin_edition`` permissions.
**Example request**
.. code-block:: http
PATCH /editions/1 HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKcFlYUWlPakUwTlRZM056SXpORGdzSW1WNGNDSTZNVFEx...
Connection: keep-alive
Content-Length: 31
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/0.9.3
{
"title": "Development master"
}
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 413
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:29 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"build_url": "http://localhost:5000/builds/2",
"date_created": "2016-03-01T10:21:29.017615Z",
"date_ended": null,
"date_rebuilt": "2016-03-01T10:21:29.590839Z",
"mode": "git_refs",
"product_url": "http://localhost:5000/products/lsst_apps",
"published_url": "pipelines.lsst.io",
"self_url": "http://localhost:5000/editions/1",
"slug": "latest",
"surrogate_key": "2a5f38f27e3c46258fd9b0e69afe54fd",
"title": "Development master",
"tracked_refs": [
"master"
]
}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param id: ID of the Edition.
:<json string build_url: URL of the build entity this Edition uses
(optional). Effectively this 'rebuilds' the edition.
:<json string title: Human-readable name for edition (optional).
:<json string slug: URL-safe name for edition (optinal). Changing the slug
dynamically updates the ``published_url``.
:<json str mode: Tracking mode.
``git_refs``: track the Git ref specified by ``tracked_refs``.
``lsst_doc``: track LSST document version tags.
:<json array tracked_refs: Git ref(s) that this Edition points to.
For multi-package documentation builds this is a list of Git refs that
are checked out, in order of priority, for each component repository
(optional).
:<json bool pending_rebuild: Semaphore indicating if a rebuild for the
edition is currently queued (optional). This should only be set
manually if the ``rebuild_edition`` task failed.
:>json string build_url: URL of the build entity this Edition uses.
:>json string date_created: UTC date time when the edition was created.
:>json string date_ended: UTC date time when the edition was deprecated;
will be ``null`` for editions that are *not deprecated*.
:>json string date_rebuilt: UTC date time when the edition last re-pointed
to a different build.
:>json str mode: Tracking mode.
``git_refs``: track the Git ref specified by ``tracked_refs``.
``lsst_doc``: track LSST document version tags.
:>json string product_url: URL of parent product entity.
:>json string published_url: Full URL where this edition is published.
:>json string self_url: URL of this Edition entity.
:>json string slug: URL-safe name for edition.
:>json string surrogate_key: Surrogate key that should be used in the
``x-amz-meta-surrogate-control`` header of any the edition's S3
objects to control Fastly caching.
:>json string title: Human-readable name for edition.
:>json string tracked_refs: Git ref that this Edition points to, for use
with the ``git_refs`` tricking mode. For multi-repository products,
this can be a comma-separated list of refs to use, in order of
priority.
:statuscode 200: No errors.
:statuscode 404: Edition resource not found.
"""
edition = Edition.query.get_or_404(id)
try:
edition.patch_data(request.json)
db.session.add(edition)
db.session.commit()
edition_json = edition.export_data()
# Run the task queue
append_task_to_chain(build_dashboard.si(edition.product.get_url()))
task = launch_task_chain()
edition_json = insert_task_url_in_response(edition_json, task)
except Exception:
db.session.rollback()
raise
return jsonify(edition_json)
| {
"repo_name": "lsst-sqre/ltd-keeper",
"path": "keeper/api/editions.py",
"copies": "1",
"size": "14022",
"license": "mit",
"hash": 4452582215047378400,
"line_mean": 32.1489361702,
"line_max": 79,
"alpha_frac": 0.6430609043,
"autogenerated": false,
"ratio": 3.6803149606299215,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48233758649299213,
"avg_score": null,
"num_lines": null
} |
"""API v1 routes for products."""
from __future__ import annotations
from typing import Dict, Tuple
from flask import jsonify, request
from flask_accept import accept_fallback
from keeper.api import api
from keeper.auth import permission_required, token_auth
from keeper.logutils import log_route
from keeper.models import Edition, Permission, Product, db
from keeper.taskrunner import (
append_task_to_chain,
insert_task_url_in_response,
launch_task_chain,
mock_registry,
)
from keeper.tasks.dashboardbuild import build_dashboard
# Register imports of celery task chain launchers
mock_registry.extend(
[
"keeper.api.products.launch_task_chain",
"keeper.api.products.append_task_to_chain",
]
)
@api.route("/products/", methods=["GET"])
@accept_fallback
@log_route()
def get_products() -> str:
"""List all documentation products (anonymous access allowed).
**Example request**
.. code-block:: http
GET /products/ HTTP/1.1
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 122
Content-Type: application/json
Date: Tue, 01 Mar 2016 17:21:27 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"products": [
"http://localhost:5000/products/lsst_apps",
"http://localhost:5000/products/qserv_distrib"
]
}
:>json array products: List of product URLs.
:statuscode 200: No error.
"""
return jsonify(
{"products": [product.get_url() for product in Product.query.all()]}
)
@api.route("/products/<slug>", methods=["GET"])
@accept_fallback
@log_route()
def get_product(slug: str) -> str:
"""Get the record of a single documentation product (anonymous access
allowed).
**Example request**
.. code-block:: http
GET /products/pipelines HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKaGJHY2lPaUpJVXpJMU5pSXNJbVY0Y0NJNk1UUTJNVEV3...
Connection: keep-alive
Host: localhost:5000
User-Agent: HTTPie/0.9.3
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 385
Content-Type: application/json
Date: Tue, 19 Apr 2016 21:17:52 GMT
Server: Werkzeug/0.11.3 Python/3.5.0
{
"bucket_name": "an-s3-bucket",
"doc_repo": "https://github.com/lsst/pipelines_docs.git",
"domain": "pipelines.lsst.io",
"fastly_domain": "pipelines.lsst.io.global.ssl.fastly.net",
"root_domain": "lsst.io",
"root_fastly_domain": "global.ssl.fastly.net",
"self_url": "http://localhost:5000/products/pipelines",
"slug": "pipelines",
"surrogate_key": "2a5f38f27e3c46258fd9b0e69afe54fd",
"title": "LSST Science Pipelines"
}
:param slug: Identifier for this product.
:>json string bucket_name: Name of the S3 bucket hosting builds.
:>json string doc_repo: URL of the Git documentation repo (i.e., on
GitHub).
:>json string domain: Full domain where this product's documentation
is served from this LSST the Docs installation is served from.
(e.g., ``pipelines.lsst.io``).
:>json string fastly_domain: Full domain where Fastly serves content
for this product. Note that ``domain`` is CNAME'd to ``fastly_domain``.
:>json string root_domain: Root domain name where documentation for
this LSST the Docs installation is served from. (e.g., ``lsst.io``).
:>json string root_fastly_domain: Root domain name for Fastly CDN used
by this LSST the Docs installation.
:>json string published_url: Full URL where this product is published to
the reader.
:>json string self_url: URL of this Product resource.
:>json string slug: URL/path-safe identifier for this product.
:>json string surrogate_key: Surrogate key that should be used in the
``x-amz-meta-surrogate-control`` header of any product-level
dashboards to control Fastly caching.
:>json string title: Human-readable product title.
:statuscode 200: No error.
:statuscode 404: Product not found.
"""
product = Product.query.filter_by(slug=slug).first_or_404()
return jsonify(product.export_data())
@api.route("/products/", methods=["POST"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_PRODUCT)
def new_product() -> Tuple[str, int, Dict[str, str]]:
"""Create a new documentation product.
Every new product also includes a default edition (slug is 'main'). This
main edition tracks the master branch by default. Fastly is configured to
show this main edition at the product's root URL rather than in the /v/
directory.
**Authorization**
User must be authenticated and have ``admin_product`` permissions.
**Example request**
.. code-block:: http
POST /products/ HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKaGJHY2lPaUpJVXpJMU5pSXNJbVY0Y0NJNk1UUTJNVEV3...
Connection: keep-alive
Content-Length: 218
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/0.9.3
{
"bucket_name": "an-s3-bucket",
"doc_repo": "https://github.com/lsst/pipelines_docs.git",
"root_domain": "lsst.io",
"root_fastly_domain": "global.ssl.fastly.net",
"slug": "pipelines",
"surrogate_key": "2a5f38f27e3c46258fd9b0e69afe54fd",
"title": "LSST Science Pipelines"
}
**Example response**
.. code-block:: http
HTTP/1.0 201 CREATED
Content-Length: 2
Content-Type: application/json
Date: Tue, 19 Apr 2016 21:17:52 GMT
Location: http://localhost:5000/products/pipelines
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:<json string bucket_name: Name of the S3 bucket hosting builds.
:<json string doc_repo: URL of the Git documentation repo (i.e., on
GitHub).
:<json str main_mode: Tracking mode for the main (default) edition.
``git_refs``: track the ``master`` branch.
``lsst_doc``: track LSST document version tags.
:<json string root_domain: Root domain name where documentation for
this LSST the Docs installation is served from. (e.g., ``lsst.io``).
:<json string root_fastly_domain: Root domain name for Fastly CDN used
by this LSST the Docs installation.
:<json string self_url: URL of this Product resource.
:<json string slug: URL/path-safe identifier for this product. The slug
is validated against the regular expression ``^[a-z]([-]*[a-z0-9])*$``.
:<json string title: Human-readable product title.
:resheader Location: URL of the created product.
:statuscode 201: No error.
"""
product = Product()
try:
request_json = request.json
product.import_data(request_json)
db.session.add(product)
db.session.flush() # Because Edition._validate_slug does not autoflush
# Create a default edition for the product
edition_data = {
"tracked_refs": ["master"],
"slug": "main",
"title": "Latest",
}
if "main_mode" in request_json:
edition_data["mode"] = request_json["main_mode"]
else:
# Default tracking mode
edition_data["mode"] = "git_refs"
edition = Edition(product=product)
edition.import_data(edition_data)
db.session.add(edition)
db.session.commit()
# Run the task queue
append_task_to_chain(build_dashboard.si(product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
except Exception:
db.session.rollback()
raise
return jsonify(response), 201, {"Location": product.get_url()}
@api.route("/products/<slug>", methods=["PATCH"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_PRODUCT)
def edit_product(slug: str) -> Tuple[str, int, Dict[str, str]]:
"""Update a product.
Note that not all fields can be updated with this method (currently).
See below for updateable fields. Contact the operator to update the slug,
bucket name, or Fastly domain.
**Authorization**
User must be authenticated and have ``admin_product`` permissions.
**Example request**
.. code-block:: http
PATCH /products/qserv HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic ZXlKaGJHY2lPaUpJVXpJMU5pSXNJbVY0Y0NJNk1UUTJNVEV3...
Connection: keep-alive
Content-Length: 30
Content-Type: application/json
Host: localhost:5000
User-Agent: HTTPie/0.9.3
{
"title": "Qserv Data Access"
}
**Example response**
.. code-block:: http
HTTP/1.0 200 OK
Content-Length: 2
Content-Type: application/json
Date: Tue, 19 Apr 2016 21:17:53 GMT
Location: http://localhost:5000/products/qserv
Server: Werkzeug/0.11.3 Python/3.5.0
{}
:reqheader Authorization: Include the token in a username field with a
blank password; ``<token>:``.
:param slug: Product slug.
:<json string doc_repo: URL of the Git documentation repo (i.e., on
GitHub) (optional).
:<json string title: Human-readable product title (optional).
:resheader Location: URL of the created product.
:statuscode 200: No error.
:statuscode 404: Product not found.
"""
product = Product.query.filter_by(slug=slug).first_or_404()
try:
product.patch_data(request.json)
db.session.add(product)
db.session.commit()
# Run the task queue
append_task_to_chain(build_dashboard.si(product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
except Exception:
db.session.rollback()
raise
return jsonify(response), 200, {"Location": product.get_url()}
@api.route("/products/<slug>/dashboard", methods=["POST"])
@accept_fallback
@log_route()
@token_auth.login_required
@permission_required(Permission.ADMIN_PRODUCT)
def rebuild_product_dashboard(slug: str) -> Tuple[str, int, Dict[str, str]]:
"""Rebuild the LTD Dasher dashboard manually for a single product.
Note that the dashboard is built asynchronously.
**Authorization**
User must be authenticated and have ``admin_product`` permissions.
:statuscode 202: Dashboard rebuild trigger sent.
**See also**
- :http:post:`/dashboards`
"""
product = Product.query.filter_by(slug=slug).first_or_404()
append_task_to_chain(build_dashboard.si(product.get_url()))
task = launch_task_chain()
response = insert_task_url_in_response({}, task)
return jsonify(response), 202, {}
| {
"repo_name": "lsst-sqre/ltd-keeper",
"path": "keeper/api/products.py",
"copies": "1",
"size": "11177",
"license": "mit",
"hash": 3300125539110220000,
"line_mean": 30.5734463277,
"line_max": 79,
"alpha_frac": 0.6440010736,
"autogenerated": false,
"ratio": 3.6742274819197895,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48182285555197896,
"avg_score": null,
"num_lines": null
} |
"""API v2 tests."""
from django.urls import reverse
from modoboa.admin import factories as admin_factories
from modoboa.admin import models as admin_models
from modoboa.dnstools import factories
from modoboa.lib.tests import ModoAPITestCase
class DNSViewSetTestCase(ModoAPITestCase):
@classmethod
def setUpTestData(cls): # NOQA:N802
"""Create test data."""
super().setUpTestData()
admin_factories.populate_database()
cls.spf_rec = factories.DNSRecordFactory(
type="spf", value="v=SPF1 mx -all", is_valid=True,
domain__name="test.com"
)
cls.dmarc_rec = factories.DNSRecordFactory(
type="dmarc", value="XXX", is_valid=False,
error="Not a DMARC record",
domain__name="test.com"
)
cls.dkim_rec = factories.DNSRecordFactory(
type="dkim", value="12345", is_valid=False,
error="Public key mismatchs",
domain__name="test.com"
)
cls.ac_rec = factories.DNSRecordFactory(
type="autoconfig", value="1.2.3.4", is_valid=True,
domain__name="test.com"
)
def test_dns_detail(self):
domain = admin_models.Domain.objects.get(name="test.com")
url = reverse("v2:dns-dns-detail", args=[domain.pk])
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["dmarc_record"]["type"], "dmarc")
| {
"repo_name": "modoboa/modoboa",
"path": "modoboa/dnstools/api/v2/tests.py",
"copies": "1",
"size": "1474",
"license": "isc",
"hash": -8027733014501985000,
"line_mean": 34.0952380952,
"line_max": 70,
"alpha_frac": 0.6153324288,
"autogenerated": false,
"ratio": 3.639506172839506,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9754838601639506,
"avg_score": 0,
"num_lines": 42
} |
"""API v2 tests."""
from django.urls import reverse
from rest_framework.authtoken.models import Token
from modoboa.admin import factories, models
from modoboa.core import models as core_models
from modoboa.lib.tests import ModoAPITestCase
class DomainViewSetTestCase(ModoAPITestCase):
@classmethod
def setUpTestData(cls): # NOQA:N802
"""Create test data."""
super().setUpTestData()
factories.populate_database()
cls.da_token = Token.objects.create(
user=core_models.User.objects.get(username="admin@test.com"))
def test_create(self):
url = reverse("v2:domain-list")
data = {
"name": "domain.tld",
"domain_admin": {
"username": "admin",
"with_mailbox": True,
"with_aliases": True
}
}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 201)
dom = models.Domain.objects.get(pk=resp.json()["pk"])
self.assertEqual(len(dom.admins), 1)
admin = dom.admins.first()
self.assertTrue(hasattr(admin, "mailbox"))
self.assertTrue(
models.Alias.objects.filter(
address="postmaster@domain.tld").exists()
)
def test_delete(self):
self.client.credentials(
HTTP_AUTHORIZATION="Token " + self.da_token.key)
domain = models.Domain.objects.get(name="test2.com")
url = reverse("v2:domain-delete", args=[domain.pk])
resp = self.client.post(url)
self.assertEqual(resp.status_code, 403)
domain = models.Domain.objects.get(name="test.com")
url = reverse("v2:domain-delete", args=[domain.pk])
resp = self.client.post(url)
self.assertEqual(resp.status_code, 403)
self.client.credentials(HTTP_AUTHORIZATION="Token " + self.token.key)
url = reverse("v2:domain-delete", args=[domain.pk])
resp = self.client.post(url)
self.assertEqual(resp.status_code, 204)
def test_administrators(self):
domain = models.Domain.objects.get(name="test.com")
url = reverse("v2:domain-administrators", args=[domain.pk])
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertEqual(len(resp.json()), 1)
def test_administrator(self):
domain = models.Domain.objects.get(name="test.com")
url = reverse("v2:domain-add-administrator", args=[domain.pk])
account = core_models.User.objects.get(username="user@test.com")
data = {"account": account.pk}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
def test_remove_adminstrator(self):
domain = models.Domain.objects.get(name="test.com")
url = reverse("v2:domain-remove-administrator", args=[domain.pk])
account = core_models.User.objects.get(username="user@test.com")
data = {"account": account.pk}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
class AccountViewSetTestCase(ModoAPITestCase):
@classmethod
def setUpTestData(cls): # NOQA:N802
"""Create test data."""
super().setUpTestData()
factories.populate_database()
def test_create(self):
url = reverse("v2:account-list")
data = {
"username": "toto@test.com",
"role": "SimpleUsers",
"mailbox": {
"use_domain_quota": True
},
"password": "Toto12345",
"language": "fr",
"aliases": ["alias3@test.com"]
}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 201)
self.assertTrue(
models.Alias.objects.filter(
address="alias3@test.com").exists()
)
def test_create_admin(self):
url = reverse("v2:account-list")
data = {
"username": "superadmin",
"role": "SuperAdmins",
"password": "Toto12345",
"language": "fr",
"aliases": ["alias3@test.com"]
}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 400)
def test_create_with_bad_password(self):
url = reverse("v2:account-list")
data = {
"username": "superadmin",
"role": "SuperAdmins",
}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 400)
self.assertIn("password", resp.json())
data["password"] = "Toto"
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 400)
self.assertIn("password", resp.json())
def test_validate(self):
data = {"username": "toto@test.com"}
url = reverse("v2:account-validate")
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 204)
def test_random_password(self):
url = reverse("v2:account-random-password")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertIn("password", resp.json())
def test_delete(self):
account = core_models.User.objects.get(username="user@test.com")
url = reverse("v2:account-delete", args=[account.pk])
resp = self.client.post(url)
self.assertEqual(resp.status_code, 204)
with self.assertRaises(core_models.User.DoesNotExist):
account.refresh_from_db()
class IdentityViewSetTestCase(ModoAPITestCase):
@classmethod
def setUpTestData(cls): # NOQA:N802
"""Create test data."""
super().setUpTestData()
factories.populate_database()
def test_list(self):
url = reverse("v2:identities-list")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertEqual(len(resp.json()), 8)
class AliasViewSetTestCase(ModoAPITestCase):
@classmethod
def setUpTestData(cls): # NOQA:N802
"""Create test data."""
super().setUpTestData()
factories.populate_database()
def test_validate(self):
url = reverse("v2:alias-validate")
data = {"address": "alias@unknown.com"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 400)
data = {"address": "alias@test.com"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 400)
data = {"address": "alias2@test.com"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 204)
def test_random_address(self):
url = reverse("v2:alias-random-address")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
self.assertIn("address", resp.json())
| {
"repo_name": "modoboa/modoboa",
"path": "modoboa/admin/api/v2/tests.py",
"copies": "1",
"size": "7006",
"license": "isc",
"hash": -9328286895874996,
"line_mean": 33.5123152709,
"line_max": 77,
"alpha_frac": 0.5977733371,
"autogenerated": false,
"ratio": 3.7585836909871246,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48563570280871243,
"avg_score": null,
"num_lines": null
} |
"""API version 1.0 models.
api/models.py
"""
import datetime
import jwt
from flask_marshmallow import Marshmallow
from werkzeug.security import generate_password_hash, check_password_hash
from flask import current_app
from api import db
ma = Marshmallow()
class AddUpdateDelete():
def add(self, resource):
db.session.add(resource)
return db.session.commit()
def update(self):
return db.session.commit()
def delete(self, resource):
db.session.delete(resource)
return db.session.commit()
class User(db.Model, AddUpdateDelete):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
password_hash = db.Column(db.String, nullable=False)
email = db.Column(db.String(150), unique=True, nullable=False)
bucketlists = db.relationship('BucketList', backref='user', lazy=True)
created_date = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def __repr__(self):
return '<User %r>' % self.username
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def encode_auth_token(self, user_id):
"""
:param user_id:
:return: string
"""
try:
payload = {
# expiration period
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=3600),
# time of creation of the token
'iat': datetime.datetime.utcnow(),
# subject of the token
'sub': user_id
}
return jwt.encode(
payload,
current_app.config.get('SECRET_KEY'),
algorithm='HS256'
)
except Exception as error:
return error
@staticmethod
def decode_auth_token(auth_token):
""""
Decodes the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY'))
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Session has expired. Login to get a new token'
except jwt.InvalidTokenError:
return 'Invalid token.'
class BucketList(db.Model, AddUpdateDelete):
__tablename__ = 'bucketlist'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
date_created = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
date_modified = db.Column(db.DateTime, nullable=True, default=datetime.datetime.now)
items = db.relationship('BucketItem', backref='bucketlist', cascade='all, delete', lazy=True)
created_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return '<BucketList %r>' % self.name
class BucketItem(db.Model, AddUpdateDelete):
__tablename__ = 'bucketitem'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
done = db.Column(db.Boolean, nullable=False, default='False')
date_created = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)
date_modified = db.Column(db.DateTime, nullable=True, default=datetime.datetime.now)
bucket_id = db.Column(db.Integer, db.ForeignKey('bucketlist.id'), nullable=False)
def __repr__(self):
return '<BucketItem %r>' % self.name
| {
"repo_name": "Mbarak-Mbigo/cp2_bucketlist",
"path": "api/models.py",
"copies": "1",
"size": "3808",
"license": "mit",
"hash": 1702551584011660000,
"line_mean": 32.4035087719,
"line_max": 97,
"alpha_frac": 0.6294642857,
"autogenerated": false,
"ratio": 3.8936605316973414,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9956763241364619,
"avg_score": 0.013272315206544446,
"num_lines": 114
} |
API_VERSIONSTRING = "V3.7.1.16"
HS_OT_CallOptions = 'C'
HS_OT_PutOptions = 'P'
HS_EI_SSE = "1"
HS_EI_SZSE = "2"
HS_EI_CZCE = "F1"
HS_EI_DCE = "F2"
HS_EI_SHFE = "F3"
HS_EI_CFFEX = "F4"
HS_EI_INE = "F5"
HS_ET_Abandon = '0'
HS_ET_Exec = '1'
HS_CSI_CNSJC = "CNSJC"
HS_CSI_PXSJC = "PXSJC"
HS_CSI_PNSJC = "PNSJC"
HS_CSI_CXSJC = "CXSJC"
HS_CSI_KS = "KS"
HS_CSI_KKS = "KKS"
HS_CSI_ZBD = "ZBD"
HS_CSI_ZXJ = "ZXJ"
HS_D_Buy = '1'
HS_D_Sell = '2'
HS_OF_Open = '1'
HS_OF_Close = '2'
HS_OF_Delivery = '3'
HS_OF_CloseToday = '4'
HS_CD_Comb = '1'
HS_CD_UnComb = '2'
HS_PT_Right = '0'
HS_PT_Voluntary = '1'
HS_PT_Covered = '2'
HS_LT_Lock = '1'
HS_LT_Unlock = '2'
HS_OS_NotReported = '0'
HS_OS_ToBeReported = '1'
HS_OS_Reported = '2'
HS_OS_ReportedToBeCancel = '3'
HS_OS_PartsTradedToBeCancel = '4'
HS_OS_CanceledWithPartsTraded = '5'
HS_OS_Canceled = '6'
HS_OS_PartsTraded = '7'
HS_OS_Traded = '8'
HS_OS_Abandoned = '9'
HS_OS_CancelFailed = 'D'
HS_OS_Confirmed = 'V'
HS_OS_ToBeConfirmed = 'W'
HS_OSRC_Personal = '0'
HS_OSRC_Exchange = '1'
HS_OSRC_Member = '2'
HS_OSRC_Organization = '3'
HS_OSRC_Proprietary = '4'
HS_OSRC_MobileServiceProvider = '5'
HS_TT_BankToBroker = '1'
HS_TT_BrokerToBank = '2'
HS_TSRC_Broker = '0'
HS_TSRC_Bank = '1'
HS_TSRC_Each = '2'
HS_TSRC_Third = '3'
HS_TS_NotReported = '0'
HS_TS_Reported = '1'
HS_TS_Success = '2'
HS_TS_Abandoned = '3'
HS_TS_ReportedToBeCancel = '4'
HS_TS_Canceled = '5'
HS_TS_PendingReversal = '7'
HS_TS_Reversal = '8'
HS_TS_ToBeReported = 'A'
HS_TS_Reporting = 'P'
HS_TS_Confirmed = 'Q'
HS_TS_PendingConfirm = 'x'
HS_HT_Speculation = '0'
HS_HT_Hedge = '1'
HS_HT_Arbitrage = '2'
HS_HT_MarketMaker = '3'
HS_HT_Covered = '4'
HS_BCF_NO = '0'
HS_BCF_YES = '1'
HS_BCFD_NO = '0'
HS_BCFD_YES = '1'
HS_IT_Init = 'S'
HS_IT_CallAuction = 'C'
HS_IT_Trinding = 'T'
HS_IT_Pause = 'B'
HS_IT_Close = 'E'
HS_IT_ClosingCallAuction = 'U'
HS_IT_Fusing = 'V'
HS_IT_Halt = 'P'
HS_IT_HaltAllDay = '1'
HS_IT_FuseToCallAuction = 'M'
HS_IT_FuseToClose = 'N'
HS_OR_LimitBidOpen = '0'
HS_OR_LimitSellOpen = '1'
HS_OR_LimitCoveredOpen = '2'
HS_MMSA_NO = '0'
HS_MMSA_YES = '1'
HS_FCR_NotForceClose = '0'
HS_FCR_LackDeposit = '1'
HS_FCR_ClientOverPositionLimit = '2'
HS_FCR_MemberOverPositionLimit = '3'
HS_FCR_NotMultiple = '4'
HS_FCR_Violation = '5'
HS_FCR_Other = '6'
HS_TF_No = '0'
HS_TF_Yes = '1'
HS_SOF_Normal = '0'
HS_SOF_Swap = '1'
HS_PWDT_Fund = '1'
HS_PWDT_Trade = '2'
HS_CT_Limit = "L"
HS_CT_LimitFOK = "LFOK"
HS_CT_LimitFAK = "LFAK"
HS_CT_LimitStopLoss = "LLOS"
HS_CT_LimitStopProfit = "LPFT"
HS_CT_Market = "M"
HS_CT_MarketFOK = "MFOK"
HS_CT_MarketFAK = "MFAK"
HS_CT_MarketFAKV = "MFAKV"
HS_CT_MarketStopLoss = "MLOS"
HS_CT_MarketStopProfit = "MPFT"
HS_CT_MarketToLimit = "MTL"
HS_CT_Market5FAK = "M5FAK"
HS_CT_Market5ToLimit = "M5TL"
HS_CT_Market1ToLimit = "M1TL"
HS_CT_Market1FAK = "M1FAK"
HS_CT_Market1FOK = "M1FOK"
HS_CT_MarketSelfToLimit = "MSTL"
HS_PTYPE_Futures = '1'
HS_PTYPE_OptFutu = '2'
HS_PTYPE_Combination = '3'
HS_PTYPE_Spot = '4'
HS_PTYPE_FutuToSpot = '5'
HS_PTYPE_Securities = '6'
HS_PTYPE_OptStock = '7'
HS_CID_CNY = '0'
HS_CID_USD = '1'
HS_CID_HKD = '2'
HS_CF_NO = '0'
HS_CF_YES = '1'
HS_COMBT_PT = '0'
HS_COMBT_KQ = '1'
HS_COMBT_KPZ = '2'
HS_RL_Default = '0'
HS_RL_Keep = '1'
HS_RL_Cautions = '2'
HS_RL_Steady = '3'
HS_RL_Active = '4'
HS_RL_Growth = '6'
HS_RL_Profession = '99'
HS_RL_Diy = '100'
HS_TT_Common = '0'
HS_TT_OptionsExecution = '1'
HS_TT_OTC = '2'
HS_TT_EFPDerived = '3'
HS_TT_CombinationDerived = '4'
HS_TERT_RESTART = "0"
HS_TERT_RESUME = "1"
HS_TERT_QUICK = "2"
| {
"repo_name": "vnpy/vnpy",
"path": "vnpy/api/uft/uft_constant.py",
"copies": "6",
"size": "3509",
"license": "mit",
"hash": 2599308808955940000,
"line_mean": 21.3503184713,
"line_max": 36,
"alpha_frac": 0.6414933029,
"autogenerated": false,
"ratio": 1.8342916884474647,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.5475784991347464,
"avg_score": null,
"num_lines": null
} |
"""API Views and ViewSets"""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.loading import get_models
from django.http import Http404
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from djes.apps import indexable_registry
import elasticsearch
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.filter import F
from rest_framework import (
filters,
status,
viewsets,
routers
)
from firebase_token_generator import create_token
from rest_framework.decorators import detail_route, list_route
from rest_framework.metadata import BaseMetadata
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from bulbs.content.custom_search import custom_search_model
from bulbs.content.filters import Authors
from bulbs.content.models import Content, Tag, LogEntry, FeatureType, ObfuscatedUrlInfo
from bulbs.content.serializers import (
ContentSerializer, LogEntrySerializer, PolymorphicContentSerializer,
TagSerializer, UserSerializer, FeatureTypeSerializer,
ObfuscatedUrlInfoSerializer
)
from bulbs.contributions.serializers import ContributionSerializer
from bulbs.contributions.models import Contribution
from bulbs.utils.methods import get_query_params, get_request_data
from .mixins import UncachedResponse
from .permissions import CanEditContent, CanPublishContent
class ContentViewMetaData(BaseMetadata):
def determine_metadata(self, request, view):
return {
'status': 'ok',
}
class ContentViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for the `bulbs.content.Content` model
"""
model = Content
queryset = Content.objects.all()
serializer_class = PolymorphicContentSerializer
include_base_doctype = False
paginate_by = 20
filter_fields = ("search", "before", "after", "status", "feature_types", "published", "tags", "authors", "types")
permission_classes = [IsAdminUser, CanEditContent]
metadata_class = ContentViewMetaData
def get_serializer_class(self):
"""gets the class type of the serializer
:return: `rest_framework.Serializer`
"""
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
# Looks like this is a detail...
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
try:
klass = doctypes[self.request.REQUEST["doctype"]]
except KeyError:
raise Http404
if hasattr(klass, "get_serializer_class"):
return klass.get_serializer_class()
# TODO: fix deprecation warning here -- `get_serializer_class` is going away soon!
return super(ContentViewSet, self).get_serializer_class()
def post_save(self, obj, created=False):
"""indexes the object to ElasticSearch after any save function (POST/PUT)
:param obj: instance of the saved object
:param created: boolean expressing if object is newly created (`False` if updated)
:return: `rest_framework.viewset.ModelViewSet.post_save`
"""
from bulbs.content.tasks import index
index.delay(obj.polymorphic_ctype_id, obj.pk)
message = "Created" if created else "Saved"
LogEntry.objects.log(self.request.user, obj, message)
return super(ContentViewSet, self).post_save(obj, created=created)
def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
for field_name in ("before", "after", "status", "published"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).get(field_name)
for field_name in ("tags", "types", "feature_types"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).getlist(field_name)
if "search" in get_query_params(self.request):
search_kwargs["query"] = get_query_params(self.request).get("search")
queryset = Content.search_objects.search(**search_kwargs)
if "authors" in get_query_params(self.request):
authors = get_query_params(self.request).getlist("authors")
queryset = queryset.filter(Authors(authors))
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
@detail_route(permission_classes=[CanPublishContent], methods=['post'])
def publish(self, request, **kwargs):
"""sets the `published` value of the `Content`
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
if "published" in get_request_data(request):
if not get_request_data(request)["published"]:
content.published = None
else:
publish_dt = parse_datetime(get_request_data(request)["published"])
if publish_dt:
publish_dt = publish_dt.astimezone(timezone.utc)
else:
publish_dt = None
content.published = publish_dt
else:
content.published = timezone.now()
content.save()
LogEntry.objects.log(request.user, content, content.get_status())
return Response({"status": content.get_status(), "published": content.published})
@detail_route(permission_classes=[CanPublishContent], methods=['post'])
def trash(self, request, **kwargs):
"""destroys a `Content` instance and removes it from the ElasticSearch index
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 404
"""
content = self.get_object()
content.indexed = False
content.save()
index = content.__class__.search_objects.mapping.index
doc_type = content.__class__.search_objects.mapping.doc_type
try:
Content.search_objects.client.delete(
index=index,
doc_type=doc_type,
id=content.id)
LogEntry.objects.log(request.user, content, "Trashed")
return Response({"status": "Trashed"})
except elasticsearch.exceptions.NotFoundError:
return Response(status=status.HTTP_404_NOT_FOUND)
@detail_route(methods=["get"])
def status(self, request, **kwargs):
"""This endpoint returns a status text, currently one of:
- "Draft" (If no publish date is set, and no item exists in the editor queue)
- "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue)
- "Published" (The published date is in the past)
- "Scheduled" (The published date is set in the future)
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
return Response({"status": content.get_status()})
@detail_route(methods=["post", "get"])
def contributions(self, request, **kwargs):
"""gets or adds contributions
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# Check if the contribution app is installed
if Contribution not in get_models():
return Response([])
queryset = Contribution.objects.filter(content=self.get_object())
if request.method == "POST":
serializer = ContributionSerializer(
queryset,
data=get_request_data(request),
many=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data)
else:
serializer = ContributionSerializer(queryset, many=True)
return Response(serializer.data)
@detail_route(methods=["post"], permission_classes=[CanEditContent])
def create_token(self, request, **kwargs):
"""Create a new obfuscated url info to use for accessing unpublished content.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = {
"content": self.get_object().id,
"create_date": get_request_data(request)["create_date"],
"expire_date": get_request_data(request)["expire_date"]
}
serializer = ObfuscatedUrlInfoSerializer(data=data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST, content_type="application/json")
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json")
@detail_route(methods=["get"], permission_classes=[CanEditContent])
def list_tokens(self, request, **kwargs):
"""List all tokens for this content instance.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# no date checking is done here to make it more obvious if there's an issue with the
# number of records. Date filtering will be done on the frontend.
infos = [ObfuscatedUrlInfoSerializer(info).data
for info in ObfuscatedUrlInfo.objects.filter(content=self.get_object())]
return Response(infos, status=status.HTTP_200_OK, content_type="application/json")
class TagViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached viewset for the `bulbs.content.Tag` model
"""
model = Tag
serializer_class = TagSerializer
paginate_by = 50
def get_queryset(self):
queryset = Tag.search_objects.search()
if "search" in self.request.REQUEST:
query_string = self.request.REQUEST["search"].lower()
queryset = queryset.query(Q("match", name=query_string) | Q("match", **{"name.raw": query_string}))
types = get_query_params(self.request).getlist("types", None)
if types:
queryset._doc_type = self.request.REQUEST["types"]
return queryset
class UserViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for the User model -- User can be whatever is defined as the default system
user model (`auth.User` or any other custom model)
"""
model = get_user_model()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
search_fields = ("first_name", "last_name", "username")
paginate_by = 20
class LogEntryViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for `bulbs.content.LogEntry` model
"""
model = LogEntry
serializer_class = LogEntrySerializer
def get_queryset(self):
"""creates the base queryset object for the serializer
:return: an instance of `django.db.models.QuerySet`
"""
qs = LogEntry.objects.all()
content_id = get_query_params(self.request).get("content", None)
if content_id:
qs = qs.filter(object_id=content_id)
return qs
def create(self, request, *args, **kwargs):
"""
Grabbing the user from request.user, and the rest of the method
is the same as ModelViewSet.create().
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 400
"""
data = get_request_data(request).copy()
data["user"] = request.user.id
serializer = self.get_serializer(data=data, files=request.FILES)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AuthorViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for the system user model limited to author groups and permissions
"""
model = get_user_model()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
search_fields = ("first_name", "last_name", "username")
def get_queryset(self):
"""created the base queryset object for the serializer limited to users within the authors
groups and having `is_staff`
:return: `django.db.models.QuerySet`
"""
author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True})
queryset = self.model.objects.filter(**author_filter).distinct()
return queryset
class FeatureTypeViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for the `bulbs.content.FeatureType` model
"""
model = FeatureType
serializer_class = FeatureTypeSerializer
paginate_by = 50
def get_queryset(self):
queryset = FeatureType.search_objects.search()
if "search" in self.request.REQUEST:
query_string = self.request.REQUEST["search"].lower()
queryset = queryset.query(Q("match", name=query_string) | Q("match", **{"name.raw": query_string}))
return queryset
class MeViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for users to get information about themselves
"""
def retrieve(self, request, *args, **kwargs):
"""gets basic information about the user
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = UserSerializer().to_representation(request.user)
# add superuser flag only if user is a superuser, putting it here so users can only
# tell if they are themselves superusers
if request.user.is_superuser:
data['is_superuser'] = True
# attempt to add a firebase token if we have a firebase secret
secret = getattr(settings, 'FIREBASE_SECRET', None)
if secret:
# use firebase auth to provide auth variables to firebase security api
firebase_auth_payload = {
'id': request.user.pk,
'username': request.user.username,
'email': request.user.email,
'is_staff': request.user.is_staff
}
data['firebase_token'] = create_token(secret, firebase_auth_payload)
return Response(data)
class ContentTypeViewSet(viewsets.ViewSet):
"""Searches doctypes of a model."""
model = Content
def list(self, request):
"""Search the doctypes for this model."""
query = get_query_params(request).get("search", "")
results = []
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
for doctype, klass in doctypes.items():
name = klass._meta.verbose_name.title()
if query.lower() in name.lower():
results.append(dict(
name=name,
doctype=doctype
))
results.sort(key=lambda x: x["name"])
return Response(dict(results=results))
class CustomSearchContentViewSet(viewsets.GenericViewSet):
"""This is for searching with a custom search filter."""
model = Content
queryset = Content.objects.all()
serializer_class = ContentSerializer
paginate_by = 20
permission_classes = [IsAdminUser, CanEditContent]
field_map = {
"feature-type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
}
def list(self, request, *args, **kwargs):
"""Filter Content with a custom search.
{
"query": SEARCH_QUERY
"preview": true
}
"preview" is optional and, when true, will include
items that would normally be removed due to "excluded_ids".
"""
queryset = self.get_filtered_queryset(get_request_data(request))
# Switch between paginated or standard style responses
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
def create(self, request, *args, **kwargs):
"""HACK: couldn't get POST to the list endpoint without
messing up POST for the other list_routes so I'm doing this.
Maybe something to do with the router?
"""
return self.list(request, *args, **kwargs)
def get_filtered_queryset(self, params, sort_pinned=True):
query = params
is_preview = params.get("preview", True)
qs = custom_search_model(
self.model, query, preview=is_preview,
sort_pinned=sort_pinned, field_map=self.field_map
)
return qs.full()
@list_route(methods=["get", "post"])
def count(self, request, **kwargs):
qs = self.get_filtered_queryset(get_request_data(request), sort_pinned=False)
return Response(dict(count=qs.count()))
@list_route(methods=["get", "post"])
def group_count(self, request, **kwargs):
params = dict(
groups=[
dict(get_request_data(request))
]
)
qs = self.get_filtered_queryset(params, sort_pinned=False)
return Response(dict(count=qs.count()))
# api router for aforementioned/defined viewsets
# note: me view is registered in urls.py
api_v1_router = routers.DefaultRouter()
api_v1_router.register(r"content", ContentViewSet, base_name="content")
api_v1_router.register(r"custom-search-content", CustomSearchContentViewSet, base_name="custom-search-content")
api_v1_router.register(r"content-type", ContentTypeViewSet, base_name="content-type")
api_v1_router.register(r"tag", TagViewSet, base_name="tag")
api_v1_router.register(r"log", LogEntryViewSet, base_name="logentry")
api_v1_router.register(r"author", AuthorViewSet, base_name="author")
api_v1_router.register(r"feature-type", FeatureTypeViewSet, base_name="feature-type")
api_v1_router.register(r"user", UserViewSet, base_name="user")
| {
"repo_name": "pombredanne/django-bulbs",
"path": "bulbs/api/views.py",
"copies": "1",
"size": "19696",
"license": "mit",
"hash": 6770155719583608000,
"line_mean": 37.0967117988,
"line_max": 117,
"alpha_frac": 0.6468826158,
"autogenerated": false,
"ratio": 4.179966044142614,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5326848659942615,
"avg_score": null,
"num_lines": null
} |
"""API Views and ViewSets"""
import datetime
from django.http import StreamingHttpResponse
from django.utils import dateparse, timezone
from elasticsearch_dsl import filter as es_filter
from rest_framework import viewsets, routers, mixins
from rest_framework.settings import api_settings
from rest_framework_nested import routers as nested_routers
from bulbs.content.filters import FeatureTypes, Tags
from .filters import ESPublishedFilterBackend, StartEndFilterBackend
from .models import (
ContributorRole, Contribution, FeatureTypeRate, FlatRate, FreelanceProfile, HourlyRate,
LineItem, OverrideProfile, ReportContent, MANUAL
)
from .renderers import (ContributionReportingRenderer,
ContentReportingRenderer,
FreelanceProfileRenderer,
LineItemRenderer)
from .csv_serializers import ContributionCSVSerializer, LineItemCSVSerializer
from .serializers import (
ContributorRoleSerializer, ContributionReportingSerializer, ContentReportingSerializer,
FeatureTypeRateSerializer, FlatRateSerializer, FreelanceProfileSerializer,
HourlyRateSerializer, LineEntrySerializer, OverrideProfileSerializer
)
from .utils import get_forced_payment_contributions
class BaseReportViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
def list(self, request):
if "csv" == self.request.QUERY_PARAMS.get('format'):
resp = StreamingHttpResponse(request.accepted_renderer.render(
{'queryset': self.get_queryset(),
'serializer': self.get_serializer_class(),
'context': self.get_serializer_context()}),
content_type="text/csv",
)
resp['Content-Disposition'] = 'attachment; filename="{}.csv"'.format(self.csv_filename)
return resp
else:
return super(BaseReportViewSet, self).list(request)
class LineItemViewSet(viewsets.ModelViewSet):
queryset = LineItem.objects.all()
serializer_class = LineEntrySerializer
start_fields = ("payment_date",)
end_fields = ("payment_date",)
filter_backends = (StartEndFilterBackend,)
paginate_by = 20
class ContributorRoleViewSet(viewsets.ModelViewSet):
serializer_class = ContributorRoleSerializer
def get_queryset(self):
queryset = ContributorRole.objects.all()
if self.request.QUERY_PARAMS.get("override", None) == "true":
queryset = queryset.exclude(payment_type=MANUAL)
return queryset
class NestedRateViewSet(viewsets.ModelViewSet):
"""filters queryset by role given the role_pk url kwarg"""
def get_queryset(self):
role_pk = self.request.parser_context["kwargs"].get("role_pk")
return self.model.objects.filter(role__pk=role_pk)
class FlatRateViewSet(NestedRateViewSet):
model = FlatRate
serializer_class = FlatRateSerializer
paginate_by = 20
class HourlyRateViewSet(NestedRateViewSet):
model = HourlyRate
serializer_class = HourlyRateSerializer
paginate_by = 20
class FeatureTypeRateViewSet(NestedRateViewSet):
model = FeatureTypeRate
serializer_class = FeatureTypeRateSerializer
paginate_by = 20
class OverrideProfileViewSet(viewsets.ModelViewSet):
model = OverrideProfile
queryset = OverrideProfile.search_objects.all()
serializer_class = OverrideProfileSerializer
class ContentReportingViewSet(BaseReportViewSet):
renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + (ContentReportingRenderer, )
serializer_class = ContentReportingSerializer
filter_backends = (ESPublishedFilterBackend,)
paginate_by = 20
csv_filename = 'ContentReport'
def get_queryset(self):
qs = ReportContent.search_objects.search()
# TODO: reintroduce forced submissions
# include, exclude = get_forced_payment_contributions(start_date, end_date)
# include_ids = include.values_list("content__id", flat=True)
# exclude_ids = exclude.values_list("content__id", flat=True)
# content = Content.objects.filter(
# contributions__gt=0
# ).filter(
# published__range=(start_date, end_date)
# ).exclude(
# pk__in=exclude_ids
# ).prefetch_related(
# "authors", "contributions"
# ).select_related(
# "feature_type"
# ).distinct() | Content.objects.filter(pk__in=include_ids).distinct()
if "feature_types" in self.request.QUERY_PARAMS:
feature_types = self.request.QUERY_PARAMS.getlist("feature_types")
qs = qs.filter(FeatureTypes(feature_types))
if "tags" in self.request.QUERY_PARAMS:
tags = self.request.QUERY_PARAMS.getlist("tags")
qs = qs.filter(Tags(tags))
# if "staff" in self.request.QUERY_PARAMS:
# staff = self.request.QUERY_PARAMS.get("staff")
# if staff == "freelance":
# contribution_content_ids = Contribution.objects.filter(
# contributor__freelanceprofile__is_freelance=True
# ).values_list(
# "content__id", flat=True
# ).distinct()
# elif staff == "staff":
# contribution_content_ids = Contribution.objects.filter(
# contributor__freelanceprofile__is_freelance=False
# ).values_list(
# "content__id", flat=True
# ).distinct()
# if contribution_content_ids:
# content = content.filter(pk__in=contribution_content_ids)
if "contributors" in self.request.QUERY_PARAMS:
contributors = self.request.QUERY_PARAMS.getlist("contributors")
qs = qs.filter(
es_filter.Terms(**{'contributions.contributor.username': contributors})
)
# contribution_content_ids = Contribution.objects.filter(
# contributor__username__in=contributors
# ).values_list(
# "content__id", flat=True
# ).distinct()
# content = content.filter(pk__in=contribution_content_ids)
return qs
class LineItemReportingViewSet(BaseReportViewSet):
renderer_classes = (
LineItemRenderer,
) + tuple(
api_settings.DEFAULT_RENDERER_CLASSES
)
paginate_by = 20
serializer_class = LineItemCSVSerializer
csv_filename = 'LineItemReport'
def get_queryset(self):
start = self.request.QUERY_PARAMS.get("start", None)
end = self.request.QUERY_PARAMS.get("end", None)
if end:
end = timezone.datetime.strptime(end, "%Y-%m-%d")
end += timezone.timedelta(days=1)
return LineItem.objects.filter(payment_date__range=(start, end))
class ReportingViewSet(BaseReportViewSet):
renderer_classes = tuple(
api_settings.DEFAULT_RENDERER_CLASSES
) + (ContributionReportingRenderer, )
filter_backends = (ESPublishedFilterBackend,)
paginate_by = 20
csv_filename = 'ContributionReport'
def get_serializer_class(self):
format = self.request.QUERY_PARAMS.get('format', None)
if format == 'csv':
return ContributionCSVSerializer
return ContributionReportingSerializer
def get_queryset(self):
qs = Contribution.search_objects.search()
feature_types = self.request.QUERY_PARAMS.getlist('feature_types')
if feature_types:
qs = qs.filter(
es_filter.Terms(**{'content.feature_type.slug': feature_types})
)
contributors = self.request.QUERY_PARAMS.getlist('contributors')
if contributors:
qs = qs.filter(
es_filter.Terms(**{'contributor.username': contributors})
)
tags = self.request.QUERY_PARAMS.getlist('tags')
if tags:
pass
staff = self.request.QUERY_PARAMS.get('staff', None)
if staff:
is_freelance = True if staff == 'freelance' else False
qs = qs.filter(
es_filter.Term(**{'contributor.is_freelance': is_freelance})
)
qs = qs.sort('id')
return ESPublishedFilterBackend().filter_queryset(self.request, qs, None)
class FreelanceReportingViewSet(BaseReportViewSet):
renderer_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES) + (FreelanceProfileRenderer, )
serializer_class = FreelanceProfileSerializer
paginate_by = 20
csv_filename = 'FreelanceReport'
def get_queryset(self):
now = timezone.now()
start_date = datetime.datetime(
year=now.year,
month=now.month,
day=1,
tzinfo=now.tzinfo
)
if "start" in self.request.GET:
start_date = dateparse.parse_date(self.request.GET["start"])
end_date = now
if "end" in self.request.GET:
end_date = dateparse.parse_date(self.request.GET["end"])
contribution_qs = Contribution.objects.all()
if "feature_types" in self.request.QUERY_PARAMS:
feature_types = self.request.QUERY_PARAMS.getlist("feature_types")
contribution_qs = contribution_qs.filter(content__feature_type__slug__in=feature_types)
if "tags" in self.request.QUERY_PARAMS:
tags = self.request.QUERY_PARAMS.getlist("tags")
contribution_qs = contribution_qs.filter(content__tags__slug__in=tags)
include, exclude = get_forced_payment_contributions(
start_date, end_date, qs=contribution_qs
)
include_ids = include.values_list('pk', flat=True).distinct()
exclude_ids = exclude.values_list('pk', flat=True).distinct()
contribution_qs = contribution_qs.filter(
content__published__range=(start_date, end_date)
) | Contribution.objects.filter(
pk__in=include_ids
)
contribution_qs = contribution_qs.exclude(pk__in=exclude_ids).distinct()
if "contributors" in self.request.QUERY_PARAMS:
contributors = self.request.QUERY_PARAMS.getlist("contributors")
contribution_qs = contribution_qs.filter(contributor__username__in=contributors)
contributor_ids = contribution_qs.values_list('contributor', flat=True).distinct()
qs = FreelanceProfile.objects.filter(contributor__in=contributor_ids)
if "staff" in self.request.QUERY_PARAMS:
staff = self.request.QUERY_PARAMS.get("staff")
if staff == "freelance":
qs = qs.filter(is_freelance=True)
elif staff == "staff":
qs = qs.filter(is_freelance=False)
return qs
api_v1_router = routers.DefaultRouter()
api_v1_router.register(r"line-items", LineItemViewSet, base_name="line-items")
# Nested routes for roles
api_v1_role_router = nested_routers.DefaultRouter()
api_v1_role_router.register(r"role", ContributorRoleViewSet, base_name="contributorrole")
nested_role_router = nested_routers.NestedSimpleRouter(api_v1_role_router, "role", lookup="role")
nested_role_router.register("flat_rates", FlatRateViewSet, base_name="flat-rate")
nested_role_router.register("hourly_rates", HourlyRateViewSet, base_name="hourly-rate")
nested_role_router.register(
"feature_type_rates", FeatureTypeRateViewSet, base_name="feature-type-rate"
)
api_v1_router.register(r"rate-overrides", OverrideProfileViewSet, base_name="rate-overrides")
api_v1_router.register(r"reporting", ReportingViewSet, base_name="contributionreporting")
api_v1_router.register(
r"line-item-reporting", LineItemReportingViewSet, base_name="line-item-reporting"
)
api_v1_router.register(r"contentreporting", ContentReportingViewSet, base_name="contentreporting")
api_v1_router.register(
r"freelancereporting", FreelanceReportingViewSet, base_name="freelancereporting"
)
| {
"repo_name": "theonion/django-bulbs",
"path": "bulbs/contributions/views.py",
"copies": "1",
"size": "11927",
"license": "mit",
"hash": -8269935978208210000,
"line_mean": 35.9256965944,
"line_max": 99,
"alpha_frac": 0.6576674772,
"autogenerated": false,
"ratio": 3.9983238350653703,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.515599131226537,
"avg_score": null,
"num_lines": null
} |
"""API Views and ViewSets"""
import datetime
from django.utils import dateparse, timezone
from rest_framework import viewsets, routers, mixins
from rest_framework.settings import api_settings
from rest_framework_csv.renderers import CSVRenderer
from .models import ContributorRole, Contribution
from .serializers import ContributorRoleSerializer, ContributionReportingSerializer, ContentReportingSerializer
from bulbs.content.models import Content
class ContributorRoleViewSet(viewsets.ModelViewSet):
queryset = ContributorRole.objects.all()
serializer_class = ContributorRoleSerializer
class ContentReportingViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
renderer_classes = (CSVRenderer, ) + tuple(api_settings.DEFAULT_RENDERER_CLASSES)
serializer_class = ContentReportingSerializer
def get_queryset(self):
now = timezone.now()
start_date = datetime.datetime(
year=now.year,
month=now.month,
day=1,
tzinfo=now.tzinfo)
if "start" in self.request.GET:
start_date = dateparse.parse_date(self.request.GET["start"])
end_date = now
if "end" in self.request.GET:
end_date = dateparse.parse_date(self.request.GET["end"])
content = Content.objects.filter(published__range=(start_date, end_date)).prefetch_related("authors", "contribution_set").select_related("feature_type")
return content
class ReportingViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
renderer_classes = (CSVRenderer, ) + tuple(api_settings.DEFAULT_RENDERER_CLASSES)
serializer_class = ContributionReportingSerializer
def get_queryset(self):
now = timezone.now()
start_date = datetime.datetime(
year=now.year,
month=now.month,
day=1,
tzinfo=now.tzinfo)
if "start" in self.request.GET:
start_date = dateparse.parse_date(self.request.GET["start"])
end_date = now
if "end" in self.request.GET:
end_date = dateparse.parse_date(self.request.GET["end"])
content = Content.objects.filter(published__range=(start_date, end_date))
content_ids = content.values_list("pk", flat=True)
contributions = Contribution.objects.filter(content__in=content_ids)
ordering = self.request.GET.get("ordering", "content")
order_options = {
"content": "content__published",
"user": "contributor__id"
}
return contributions.order_by(order_options[ordering])
api_v1_router = routers.DefaultRouter()
api_v1_router.register(r"role", ContributorRoleViewSet, base_name="contributorrole")
api_v1_router.register(r"reporting", ReportingViewSet, base_name="contributionreporting")
api_v1_router.register(r"contentreporting", ContentReportingViewSet, base_name="contentreporting")
| {
"repo_name": "pombredanne/django-bulbs",
"path": "bulbs/contributions/views.py",
"copies": "1",
"size": "2901",
"license": "mit",
"hash": -5324259239207334000,
"line_mean": 34.3780487805,
"line_max": 160,
"alpha_frac": 0.6938986556,
"autogenerated": false,
"ratio": 3.9903713892709765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5184270044870977,
"avg_score": null,
"num_lines": null
} |
"""API Views and ViewSets"""
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import resolve, Resolver404
from django.core.mail import EmailMessage
from django.db.models.loading import get_models
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.template import loader
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from djes.apps import indexable_registry
from elasticsearch_dsl.query import Q
from elasticsearch_dsl import filter as es_filter
from firebase_token_generator import create_token
from rest_framework import (
filters,
status,
viewsets,
routers
)
from rest_framework.decorators import detail_route, list_route
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from bulbs.content.custom_search import custom_search_model
from bulbs.content.filters import Authors
from bulbs.content.models import Content, Tag, LogEntry, FeatureType, ObfuscatedUrlInfo
from bulbs.content.serializers import (
ContentSerializer, LogEntrySerializer, PolymorphicContentSerializer,
TagSerializer, UserSerializer, FeatureTypeSerializer,
ObfuscatedUrlInfoSerializer
)
from bulbs.contributions.tasks import run_contributor_email_report
from bulbs.contributions.models import Contribution
from bulbs.contributions.serializers import ContributionSerializer, ContributorReportSerializer
from bulbs.notifications.viewsets import NotificationViewSet
from bulbs.special_coverage.models import SpecialCoverage
from bulbs.special_coverage.serializers import SpecialCoverageSerializer
from bulbs.super_features.utils import get_superfeature_model
from bulbs.utils.methods import get_query_params, get_request_data
from .metadata import PolymorphicContentMetadata
from .mixins import UncachedResponse
from .permissions import CanEditContent, CanPublishContent
class ContentViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for the `bulbs.content.Content` model
"""
model = Content
queryset = Content.objects.all()
serializer_class = PolymorphicContentSerializer
include_base_doctype = False
paginate_by = 20
filter_fields = (
"search", "before", "after", "status",
"feature_types", "published", "tags",
"authors", "types"
)
permission_classes = [IsAdminUser, CanEditContent]
metadata_class = PolymorphicContentMetadata
def get_serializer_class(self):
"""gets the class type of the serializer
:return: `rest_framework.Serializer`
"""
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
# Looks like this is a detail...
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
try:
klass = doctypes[self.request.REQUEST["doctype"]]
except KeyError:
raise Http404
if hasattr(klass, "get_serializer_class"):
return klass.get_serializer_class()
# TODO: fix deprecation warning here -- `get_serializer_class` is going away soon!
return super(ContentViewSet, self).get_serializer_class()
def post_save(self, obj, created=False):
"""indexes the object to ElasticSearch after any save function (POST/PUT)
:param obj: instance of the saved object
:param created: boolean expressing if object is newly created (`False` if updated)
:return: `rest_framework.viewset.ModelViewSet.post_save`
"""
from bulbs.content.tasks import index
index.delay(obj.polymorphic_ctype_id, obj.pk)
message = "Created" if created else "Saved"
LogEntry.objects.log(self.request.user, obj, message)
return super(ContentViewSet, self).post_save(obj, created=created)
def list(self, request, *args, **kwargs):
"""Modified list view to driving listing from ES"""
search_kwargs = {"published": False}
for field_name in ("before", "after", "status", "published"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).get(field_name)
for field_name in ("tags", "types", "feature_types"):
if field_name in get_query_params(self.request):
search_kwargs[field_name] = get_query_params(self.request).getlist(field_name)
if "search" in get_query_params(self.request):
search_kwargs["query"] = get_query_params(self.request).get("search")
queryset = self.model.search_objects.search(**search_kwargs)
if "authors" in get_query_params(self.request):
authors = get_query_params(self.request).getlist("authors")
queryset = queryset.filter(Authors(authors))
if "exclude" in get_query_params(self.request):
exclude = get_query_params(self.request).get("exclude")
queryset = queryset.filter(
es_filter.Not(es_filter.Type(**{'value': exclude}))
)
# always filter out Super Features from listing page
queryset = queryset.filter(
es_filter.Not(filter=es_filter.Type(
value=get_superfeature_model().search_objects.mapping.doc_type))
)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
@detail_route(permission_classes=[CanPublishContent], methods=['post'])
def publish(self, request, **kwargs):
"""sets the `published` value of the `Content`
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
if "published" in get_request_data(request):
if not get_request_data(request)["published"]:
content.published = None
else:
publish_dt = parse_datetime(get_request_data(request)["published"])
if publish_dt:
publish_dt = publish_dt.astimezone(timezone.utc)
else:
publish_dt = None
content.published = publish_dt
else:
content.published = timezone.now()
content.save()
LogEntry.objects.log(request.user, content, content.get_status())
return Response({"status": content.get_status(), "published": content.published})
@detail_route(permission_classes=[CanPublishContent], methods=['post'])
def trash(self, request, **kwargs):
"""Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
content.indexed = False
content.save()
LogEntry.objects.log(request.user, content, "Trashed")
return Response({"status": "Trashed"})
@detail_route(methods=["get"])
def status(self, request, **kwargs):
"""This endpoint returns a status text, currently one of:
- "Draft" (If no publish date is set, and no item exists in the editor queue)
- "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue)
- "Published" (The published date is in the past)
- "Scheduled" (The published date is set in the future)
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
content = self.get_object()
return Response({"status": content.get_status()})
@detail_route(methods=["post", "get"])
def contributions(self, request, **kwargs):
"""gets or adds contributions
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# Check if the contribution app is installed
if Contribution not in get_models():
return Response([])
if request.method == "POST":
serializer = ContributionSerializer(data=get_request_data(request), many=True)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data)
else:
content_pk = kwargs.get('pk', None)
if content_pk is None:
return Response([], status=status.HTTP_404_NOT_FOUND)
queryset = Contribution.search_objects.search().filter(
es_filter.Term(**{'content.id': content_pk})
)
serializer = ContributionSerializer(queryset[:queryset.count()].sort('id'), many=True)
return Response(serializer.data)
@detail_route(methods=["post"], permission_classes=[CanEditContent])
def create_token(self, request, **kwargs):
"""Create a new obfuscated url info to use for accessing unpublished content.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = {
"content": self.get_object().id,
"create_date": get_request_data(request)["create_date"],
"expire_date": get_request_data(request)["expire_date"]
}
serializer = ObfuscatedUrlInfoSerializer(data=data)
if not serializer.is_valid():
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST,
content_type="application/json",
)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK, content_type="application/json")
@detail_route(methods=["get"], permission_classes=[CanEditContent])
def list_tokens(self, request, **kwargs):
"""List all tokens for this content instance.
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
# no date checking is done here to make it more obvious if there's an issue with the
# number of records. Date filtering will be done on the frontend.
infos = [ObfuscatedUrlInfoSerializer(info).data
for info in ObfuscatedUrlInfo.objects.filter(content=self.get_object())]
return Response(infos, status=status.HTTP_200_OK, content_type="application/json")
class TagViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached viewset for the `bulbs.content.Tag` model
"""
model = Tag
serializer_class = TagSerializer
paginate_by = 50
def get_queryset(self):
queryset = Tag.search_objects.search()
if "search" in self.request.REQUEST:
query_string = self.request.REQUEST["search"].lower()
queryset = queryset.query(
Q("match", name=query_string) | Q("match", **{"name.raw": query_string})
)
types = get_query_params(self.request).getlist("types", None)
if types:
queryset._doc_type = self.request.REQUEST["types"]
return queryset
class UserViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for the User model -- User can be whatever is defined as the default system
user model (`auth.User` or any other custom model)
"""
model = get_user_model()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
search_fields = ("first_name", "last_name", "username")
paginate_by = 20
class LogEntryViewSet(UncachedResponse, viewsets.ModelViewSet):
"""
uncached viewset for `bulbs.content.LogEntry` model
"""
model = LogEntry
serializer_class = LogEntrySerializer
def get_queryset(self):
"""creates the base queryset object for the serializer
:return: an instance of `django.db.models.QuerySet`
"""
qs = LogEntry.objects.all()
content_id = get_query_params(self.request).get("content", None)
if content_id:
qs = qs.filter(object_id=content_id)
return qs
def create(self, request, *args, **kwargs):
"""
Grabbing the user from request.user, and the rest of the method
is the same as ModelViewSet.create().
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
:raise: 400
"""
data = get_request_data(request).copy()
data["user"] = request.user.id
serializer = self.get_serializer(data=data, files=request.FILES)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data,
status=status.HTTP_201_CREATED,
headers=headers
)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AuthorViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for the system user model limited to author groups and permissions
"""
model = get_user_model()
serializer_class = UserSerializer
filter_backends = (filters.SearchFilter, filters.OrderingFilter)
search_fields = ("first_name", "last_name", "username")
def get_queryset(self):
"""created the base queryset object for the serializer limited to users within the authors
groups and having `is_staff`
:return: `django.db.models.QuerySet`
"""
author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True})
queryset = self.model.objects.filter(**author_filter).distinct()
return queryset
class FeatureTypeViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for the `bulbs.content.FeatureType` model
"""
model = FeatureType
serializer_class = FeatureTypeSerializer
paginate_by = 50
def get_queryset(self):
queryset = FeatureType.search_objects.search()
if "search" in self.request.REQUEST:
query_string = self.request.REQUEST["search"].lower()
queryset = queryset.query(
Q("match", name=query_string) | Q("match", **{"name.raw": query_string})
)
return queryset
class MeViewSet(UncachedResponse, viewsets.ReadOnlyModelViewSet):
"""
uncached readonly viewset for users to get information about themselves
"""
def retrieve(self, request, *args, **kwargs):
"""gets basic information about the user
:param request: a WSGI request object
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response`
"""
data = UserSerializer().to_representation(request.user)
# add superuser flag only if user is a superuser, putting it here so users can only
# tell if they are themselves superusers
if request.user.is_superuser:
data['is_superuser'] = True
# attempt to add a firebase token if we have a firebase secret
secret = getattr(settings, 'FIREBASE_SECRET', None)
if secret:
# use firebase auth to provide auth variables to firebase security api
firebase_auth_payload = {
'id': request.user.pk,
'username': request.user.username,
'email': request.user.email,
'is_staff': request.user.is_staff
}
data['firebase_token'] = create_token(secret, firebase_auth_payload)
return Response(data)
class ContentTypeViewSet(viewsets.ViewSet):
"""Searches doctypes of a model."""
model = Content
def list(self, request):
"""Search the doctypes for this model."""
query = get_query_params(request).get("search", "")
results = []
base = self.model.get_base_class()
doctypes = indexable_registry.families[base]
for doctype, klass in doctypes.items():
name = klass._meta.verbose_name.title()
if query.lower() in name.lower():
results.append(dict(
name=name,
doctype=doctype
))
results.sort(key=lambda x: x["name"])
return Response(dict(results=results))
class ContentResolveViewSet(viewsets.ReadOnlyModelViewSet):
"""Retrieve content corresponding to absolute URL"""
model = Content
def list(self, request):
url = get_query_params(self.request).get("url")
if url:
try:
match = resolve(urlparse(url).path)
except Resolver404:
raise Http404("No content found matching UUID")
content = get_object_or_404(Content, pk=match.kwargs.get('pk'))
return Response(ContentSerializer(content).data)
else:
raise Http404('Must specify content "url" param')
class SpecialCoverageResolveViewSet(viewsets.ReadOnlyModelViewSet):
"""Retrieve special coverage containing specified content"""
model = SpecialCoverage
def list(self, request):
content_id = get_query_params(self.request).get("content_id")
if content_id:
content = get_object_or_404(Content, pk=content_id)
# Find special coverage via percolator
special_coverage_filter = {
"filter": {
"prefix": {"_id": "specialcoverage"}
}
}
search_objects = type(content).search_objects
results = search_objects.client.percolate(
index=search_objects.mapping.index,
doc_type=search_objects.mapping.doc_type,
id=content.id,
body=special_coverage_filter,
)
# Translate perocolator results into SpecialCoverage objects
if results["total"]:
special_coverage_ids = [int(m["_id"].split(".")[-1]) for m in results["matches"]]
qs = SpecialCoverage.objects.filter(id__in=special_coverage_ids)
# Active Filter
active = get_query_params(self.request).get('active', '').lower()
now = timezone.now()
if active == 'true':
qs = qs.filter(
start_date__lte=now, end_date__gte=now
) | qs.filter(
start_date__lte=now, end_date__isnull=True
)
elif active == 'false':
qs = qs.exclude(
start_date__lte=now, end_date__gte=now
) | qs.exclude(
start_date__lte=now, end_date__isnull=False
)
# Sponsored Filter
sponsored = get_query_params(self.request).get('sponsored', '').lower()
if sponsored == 'true':
qs = qs.filter(tunic_campaign_id__isnull=False)
elif sponsored == 'false':
qs = qs.exclude(tunic_campaign_id__isnull=False)
serializer = SpecialCoverageSerializer(qs, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
else:
raise Http404('Must specify "content_id" param')
class CustomSearchContentViewSet(viewsets.GenericViewSet):
"""This is for searching with a custom search filter."""
model = Content
queryset = Content.objects.all()
serializer_class = ContentSerializer
paginate_by = 20
permission_classes = [IsAdminUser, CanEditContent]
field_map = {
"feature-type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
}
def list(self, request, *args, **kwargs):
"""Filter Content with a custom search.
{
"query": SEARCH_QUERY
"preview": true
}
"preview" is optional and, when true, will include
items that would normally be removed due to "excluded_ids".
"""
queryset = self.get_filtered_queryset(get_request_data(request))
# Switch between paginated or standard style responses
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
def create(self, request, *args, **kwargs):
"""HACK: couldn't get POST to the list endpoint without
messing up POST for the other list_routes so I'm doing this.
Maybe something to do with the router?
"""
return self.list(request, *args, **kwargs)
def get_filtered_queryset(self, params, sort_pinned=True):
query = params
is_preview = params.get("preview", True)
qs = custom_search_model(
self.model, query, preview=is_preview,
sort_pinned=sort_pinned, field_map=self.field_map
)
return qs.full()
@list_route(methods=["get", "post"])
def count(self, request, **kwargs):
qs = self.get_filtered_queryset(get_request_data(request), sort_pinned=False)
return Response(dict(count=qs.count()))
@list_route(methods=["get", "post"])
def group_count(self, request, **kwargs):
params = dict(
groups=[
dict(get_request_data(request))
]
)
qs = self.get_filtered_queryset(params, sort_pinned=False)
return Response(dict(count=qs.count()))
class SendContributorReport(viewsets.GenericViewSet):
"""Send contribution report email to all relevant ."""
serializer_class = ContributorReportSerializer
permission_classes = [IsAdminUser, CanEditContent]
def create(self, request, *args, **kwargs):
data = ContributorReportSerializer().to_internal_value(self.request.DATA)
run_contributor_email_report.delay(**data)
return Response(status=status.HTTP_200_OK)
class ReportBugEmail(APIView):
def post(self, request):
SETTINGS = getattr(settings, "BUG_REPORTER", {})
report = request.DATA.get("report", "")
url = request.DATA.get("url", "")
user_agent = request.DATA.get("user_agent", "")
if request.user.first_name and request.user.last_name:
name = request.user.get_full_name()
else:
name = request.user.get_username()
mail = EmailMessage(
subject=SETTINGS.get("EMAIL_SUBJECT", "Hey! A bug was reported!"),
body=loader.render_to_string(
SETTINGS.get("EMAIL_TEMPLATE_PATH", "__bug_report_email.html"),
{
"report": report,
"url": url,
"user_agent": user_agent,
"submitted_by": name
}
),
from_email=request.user.email,
to=SETTINGS.get("EMAIL_TO_ADDRESSES", ["webtech@theonion.com"])
)
mail.send()
return Response({"message": "Message Sent!"}, status=status.HTTP_200_OK)
# api router for aforementioned/defined viewsets
# note: me view is registered in urls.py
api_v1_router = routers.DefaultRouter()
api_v1_router.register(r"author", AuthorViewSet, base_name="author")
api_v1_router.register(r"content", ContentViewSet, base_name="content")
api_v1_router.register(r"content-resolve", ContentResolveViewSet, base_name="content-resolve")
api_v1_router.register(r"content-type", ContentTypeViewSet, base_name="content-type")
api_v1_router.register(r"contributor-email", SendContributorReport, base_name="contributor-email")
api_v1_router.register(r"custom-search-content", CustomSearchContentViewSet,
base_name="custom-search-content")
api_v1_router.register(r"notification", NotificationViewSet, base_name="notification")
api_v1_router.register(r"feature-type", FeatureTypeViewSet, base_name="feature-type")
api_v1_router.register(r"log", LogEntryViewSet, base_name="logentry")
api_v1_router.register(r"special-coverage-resolve", SpecialCoverageResolveViewSet,
base_name="special-coverage-resolve")
api_v1_router.register(r"tag", TagViewSet, base_name="tag")
api_v1_router.register(r"user", UserViewSet, base_name="user")
| {
"repo_name": "theonion/django-bulbs",
"path": "bulbs/api/views.py",
"copies": "1",
"size": "25841",
"license": "mit",
"hash": -7718534135161639000,
"line_mean": 37.6841317365,
"line_max": 100,
"alpha_frac": 0.6315545064,
"autogenerated": false,
"ratio": 4.220316838151233,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5351871344551233,
"avg_score": null,
"num_lines": null
} |
"""API viewsets."""
from rest_framework import filters, mixins, permissions, viewsets
from . import models
from . import serializers
class EmailProviderViewSet(viewsets.ModelViewSet):
"""ViewSet class for EmailProvider."""
filter_backends = (filters.SearchFilter, )
permission_classes = (
permissions.IsAuthenticated,
permissions.DjangoModelPermissions
)
queryset = models.EmailProvider.objects.all().prefetch_related("domains")
search_fields = ("name", )
serializer_class = serializers.EmailProviderSerializer
class MigrationViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
"""ViewSet class for Migration."""
filter_backends = (filters.SearchFilter, )
permission_classes = (
permissions.IsAuthenticated,
permissions.DjangoModelPermissions
)
queryset = models.Migration.objects.all().select_related(
"provider", "mailbox__domain")
search_fields = (
"username", "provider__name", "mailbox__address",
"mailbox__domain__name")
serializer_class = serializers.MigrationSerializer
| {
"repo_name": "modoboa/modoboa-imap-migration",
"path": "modoboa_imap_migration/viewsets.py",
"copies": "1",
"size": "1225",
"license": "isc",
"hash": -2822384685650824700,
"line_mean": 31.2368421053,
"line_max": 77,
"alpha_frac": 0.6751020408,
"autogenerated": false,
"ratio": 4.748062015503876,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5923164056303877,
"avg_score": null,
"num_lines": null
} |
"""API viewsets test cases."""
from unittest import mock
from django.urls import reverse
from modoboa.admin import factories as admin_factories
from modoboa.lib.tests import ModoAPITestCase
from .. import models
class AccountViewSetTestCase(ModoAPITestCase):
"""Account viewset tests."""
@classmethod
def setUpTestData(cls):
super().setUpTestData()
admin_factories.populate_database()
@mock.patch("django_otp.plugins.otp_totp.models.TOTPDevice.verify_token")
def test_tfa_setup_process(self, verify_mock):
admin = models.User.objects.get(username="admin")
self.client.force_login(admin)
# First, check if we're in the initial state
security_url = reverse("core:user_security")
response = self.client.get(security_url)
self.assertIn("not yet activated for", response.json()["content"])
# Start setup sequence
url = reverse("api:account-tfa-setup")
response = self.client.post(url)
self.assertEqual(response.status_code, 200)
# Check if security page is up-to-date
security_url = reverse("core:user_security")
response = self.client.get(security_url)
self.assertIn("FreeOTP", response.json()["content"])
# Continue setup sequence
verify_mock.side_effect = [True]
url = reverse("api:account-tfa-setup-check")
data = {"pin_code": "1234"}
response = self.client.post(url, data, format="json")
self.assertEqual(response.status_code, 200)
# Display recovery tokens
security_url = reverse("core:user_security")
response = self.client.get(security_url)
self.assertIn("recovery codes", response.json()["content"])
admin.refresh_from_db()
self.assertTrue(admin.tfa_enabled)
device = admin.staticdevice_set.first()
self.assertIsNot(device, None)
self.assertEqual(device.token_set.count(), 10)
# Try to disable TFA auth
url = reverse("api:account-tfa-disable")
response = self.client.post(url)
self.assertEqual(response.status_code, 200)
self.assertFalse(admin.totpdevice_set.exists())
def test_tfa_reset_codes(self):
admin = models.User.objects.get(username="admin")
self.client.force_login(admin)
url = reverse("api:account-tfa-reset-codes")
response = self.client.post(url)
self.assertEqual(response.status_code, 403)
device = admin.staticdevice_set.create(name="Device")
response = self.client.post(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(device.token_set.count(), 10)
| {
"repo_name": "modoboa/modoboa",
"path": "modoboa/core/tests/test_viewsets.py",
"copies": "1",
"size": "2686",
"license": "isc",
"hash": -2888151352362224600,
"line_mean": 35.2972972973,
"line_max": 77,
"alpha_frac": 0.6567386448,
"autogenerated": false,
"ratio": 3.8591954022988504,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.501593404709885,
"avg_score": null,
"num_lines": null
} |
"""API Views for certificate generation"""
import io
import logging
import rest_framework
import zipfile
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotFound
from django.views.generic import View
from rest_framework import generics, permissions
from rest_framework.pagination import PageNumberPagination
from api.mixins import TrapDjangoValidationErrorCreateMixin
from api.serializers import CertificateCRLSerializer, CertificateRevokeSerializer, CertificateSerializer
from x509_pki.models import Certificate, CertificateTypes
logger = logging.getLogger(__name__)
class APIPageNumberPagination(PageNumberPagination):
page_size = 10
class CertificateListView(
TrapDjangoValidationErrorCreateMixin,
generics.ListCreateAPIView):
model = Certificate
serializer_class = CertificateSerializer
permission_classes = [
permissions.IsAuthenticated
]
search_fields = ('shortname', 'name',)
pagination_class = APIPageNumberPagination
filter_fields = ('type', 'parent',)
def get(self, request, *args, **kwargs):
return generics.ListCreateAPIView.get(self, request, *args, **kwargs)
def get_queryset(self):
"""
This view should return a list of all the purchases
for the currently authenticated user.
"""
user = self.request.user
return Certificate.objects.filter(owner=user)
def create(self, request, *args, **kwargs):
request.data['owner'] = request.user.id
return generics.ListCreateAPIView.create(
self, request, *args, **kwargs)
class CertificateInstanceView(generics.RetrieveAPIView):
model = Certificate
serializer_class = CertificateSerializer
permission_classes = [
permissions.IsAuthenticated
]
def get_queryset(self):
user = self.request.user
return Certificate.objects.filter(owner=user)
class IsCertificateOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if obj and request.user.id == obj.owner.id:
return True
return False
class CertificateRevokeView(generics.UpdateAPIView):
model = Certificate
serializer_class = CertificateRevokeSerializer
queryset = Certificate.objects.all()
permission_classes = [
permissions.IsAuthenticated,
IsCertificateOwner
]
class CertificateCRLView(generics.UpdateAPIView):
model = Certificate
serializer_class = CertificateCRLSerializer
queryset = Certificate.objects.all()
permission_classes = [
permissions.IsAuthenticated,
IsCertificateOwner
]
class CertificateInfoView(View):
def get(self, request, pk, *args, **kwargs):
cert = None
try:
user = self.request.user
cert = Certificate.objects.get(pk=pk, owner=user)
except Exception:
return HttpResponseNotFound("File not found")
info = cert.get_certificate_info()
return HttpResponse(info)
class FileView(View):
@staticmethod
def read_file(filename):
with open(filename, 'rb') as f:
file_content = f.read()
return file_content
@classmethod
def generate_path(cls, certificate):
prefix_path = ""
if certificate.parent and certificate.pk != certificate.parent.pk:
prefix_path = cls.generate_path(certificate.parent)
return prefix_path + "/" + str(certificate.shortname)
@classmethod
def get_root_cert_path(cls, certificate):
if certificate.parent and certificate.pk != certificate.parent.pk:
return cls.get_root_cert_path(certificate.parent)
else:
root_cert_path = settings.CERTIFICATE_REPO_PATH + "/" + \
str(certificate.shortname) + "/certs/" + str(certificate.shortname) + ".cert.pem"
return root_cert_path
class CertificateCRLFileView(FileView):
def get(self, request, pk, *args, **kwargs):
cert = None
user = None
try:
user = self.request.user
cert = Certificate.objects.get(pk=pk, owner=user)
except Exception:
return HttpResponseNotFound("File not found")
key_path = settings.CERTIFICATE_REPO_PATH + self.generate_path(cert)
if cert.type is CertificateTypes.INTERMEDIATE:
orig_file = key_path + "/crl/" + cert.shortname + ".crl.pem"
try:
file_content = self.read_file(orig_file)
filename = "%s.crl" % (cert.shortname)
response = HttpResponse(
file_content, content_type='application/octet-stream')
response[
'Content-Disposition'] = ('attachment; filename=%s' % (filename))
return response
except FileNotFoundError:
return HttpResponseNotFound("File not found")
return HttpResponseNotFound("File not found")
class CertificateFilesView(FileView):
@classmethod
def make_certificate_zip_response(cls, key_path, cert, cert_type):
root_cert_file = cls.get_root_cert_path(cert)
root_cert_file_content = cls.read_file(root_cert_file)
cert_chain_file = key_path + "/certs/" + cert_type + \
"/" + cert.shortname + "-chain.cert.pem"
cert_chain_file_content = cls.read_file(cert_chain_file)
cert_file = key_path + "/certs/" + cert_type + "/" + cert.shortname + ".cert.pem"
cert_file_content = cls.read_file(cert_file)
csr_file = key_path + "/csr/" + cert_type + "/" + cert.shortname + ".csr.pem"
csr_file_content = cls.read_file(csr_file)
key_file = key_path + "/private/" + cert_type + "/" + cert.shortname + ".key.pem"
key_file_content = cls.read_file(key_file)
p12_file = key_path + "/private/" + cert_type + "/" + cert.shortname + ".p12"
p12_file_content = cls.read_file(p12_file)
zipped_file = io.BytesIO()
with zipfile.ZipFile(zipped_file, 'w') as f:
f.writestr("rootca.pem", root_cert_file_content)
f.writestr(cert.shortname + ".csr", csr_file_content)
f.writestr(cert.shortname + ".pem", cert_file_content)
f.writestr(cert.shortname + "-chain.pem", cert_chain_file_content)
f.writestr(cert.shortname + ".key", key_file_content)
f.writestr(cert.shortname + ".p12", p12_file_content)
zipped_file.seek(0)
filename = "%s.server_cert.zip" % (cert.shortname)
response = HttpResponse(zipped_file,
content_type='application/octet-stream')
response[
'Content-Disposition'] = ('attachment; filename=%s' % (filename))
return response
def get(self, request, pk, *args, **kwargs):
cert = None
user = None
try:
user = self.request.user
cert = Certificate.objects.get(pk=pk, owner=user)
except Exception:
return HttpResponseNotFound("File not found")
key_path = settings.CERTIFICATE_REPO_PATH + self.generate_path(cert)
if cert.type is CertificateTypes.ROOT:
orig_file = key_path + "/certs/" + cert.shortname + ".cert.pem"
try:
file_content = self.read_file(orig_file)
filename = "%s.pem" % (cert.shortname)
response = HttpResponse(
file_content, content_type='application/octet-stream')
response[
'Content-Disposition'] = ('attachment; filename=%s' % (filename))
return response
except FileNotFoundError:
return HttpResponseNotFound("File not found")
if cert.type is CertificateTypes.INTERMEDIATE:
orig_file = key_path + "/certs/" + cert.shortname + "-chain.cert.pem"
try:
file_content = self.read_file(orig_file)
filename = "%s-chain.pem" % (cert.shortname)
response = HttpResponse(
file_content, content_type='application/octet-stream')
response[
'Content-Disposition'] = ('attachment; filename=%s' % (filename))
return response
except FileNotFoundError:
return HttpResponseNotFound("File not found")
key_path = settings.CERTIFICATE_REPO_PATH + self.generate_path(cert.parent)
if cert.type is CertificateTypes.SERVER_CERT:
try:
response = self.make_certificate_zip_response(
key_path, cert, "server_cert")
return response
except FileNotFoundError:
return HttpResponseNotFound("File not found")
if cert.type is CertificateTypes.CLIENT_CERT:
try:
response = self.make_certificate_zip_response(
key_path, cert, "usr_cert")
return response
except FileNotFoundError:
return HttpResponseNotFound("File not found")
return HttpResponseNotFound("File not found")
| {
"repo_name": "repleo/bounca",
"path": "api/views.py",
"copies": "1",
"size": "9201",
"license": "apache-2.0",
"hash": -8457099899022678000,
"line_mean": 35.9518072289,
"line_max": 104,
"alpha_frac": 0.619932616,
"autogenerated": false,
"ratio": 4.263670064874884,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5383602680874884,
"avg_score": null,
"num_lines": null
} |
"""API views for social_network."""
from rest_framework import viewsets
from rest_framework.decorators import api_view, detail_route
from rest_framework.response import Response
from rest_framework.reverse import reverse
from .models import Profile, Post, Vote
from .serializers import ProfileSerializer, PostSerializer
@api_view(['GET'])
def api_root(request, format=None):
"""Root of API, this is useful for documentation generated by DRF."""
return Response({
'profiles': reverse('profile-list', request=request, format=format),
'posts': reverse('post-list', request=request, format=format)
})
class ProfileViewSet(viewsets.ReadOnlyModelViewSet):
"""This provides get and list functionality for Profiles."""
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class PostViewSet(viewsets.ModelViewSet):
"""Get or create Posts.
retrieve:
Return a post given its ID.
list:
Get a paginated list of all Posts.
create:
Create a new Post as the logged-in user.
"""
queryset = Post.objects.all().order_by('-created')
serializer_class = PostSerializer
def perform_create(self, serializer):
"""Create a Post associated with the logged-in user."""
serializer.save(owner=self.request.user.profile)
@detail_route(methods=['POST', 'DELETE'], url_path='vote')
def vote(self, request, pk=None):
"""Vote or unvote on a post."""
post = self.get_object()
if request.method == 'POST':
# check if the vote already exists, if so don't allow the user to vote again
if Vote.objects.filter(profile=self.request.user.profile, post=post).exists():
# the user already voted, just return the post directly
data = PostSerializer(post, context={'request': self.request}).data
return Response(data)
new_vote = Vote(profile=self.request.user.profile, post=post)
new_vote.save()
elif request.method == 'DELETE':
Vote.objects.filter(profile=self.request.user.profile, post=post).delete()
data = PostSerializer(post, context={'request': self.request}).data
return Response(data)
| {
"repo_name": "ctcusc/django-react-boilerplate",
"path": "server/social_network/views.py",
"copies": "1",
"size": "2245",
"license": "apache-2.0",
"hash": 574262935045386560,
"line_mean": 33.5384615385,
"line_max": 90,
"alpha_frac": 0.6690423163,
"autogenerated": false,
"ratio": 4.157407407407407,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007019073972848598,
"num_lines": 65
} |
# api/views/mark.py
from flask import g
from flask.ext.restful import fields, marshal_with, reqparse, abort, marshal
from ..core.setup import Resource, auth, db
from ..core.customfields import TagList
from ..core.validators import validate_url
from ..models import Mark
mark_fields = {
'id': fields.Integer,
'type': fields.String,
'title': fields.String,
'url': fields.String,
'tags': TagList,
'clicks': fields.Integer,
'last_clicked': fields.DateTime,
'created': fields.DateTime,
'updated': fields.DateTime
}
def is_url(value):
try:
validate_url(value)
return value
except ValueError as e:
raise ValueError(e)
class Mark(Resource):
@auth.login_required
@marshal_with(mark_fields)
def get(self, mark_id):
mark = g.user.get_mark_by_id(mark_id)
if mark:
return mark
return abort(410, message="Mark {} doesn't exist".format(mark_id))
@auth.login_required
@marshal_with(mark_fields)
def put(self, mark_id):
put_parser = reqparse.RequestParser()
put_parser.add_argument('type', type=str)
put_parser.add_argument('title', type=str)
put_parser.add_argument('url', type=str)
put_parser.add_argument('tags', type=str)
args = put_parser.parse_args()
mark = g.user.get_mark_by_id(mark_id)
if mark:
return mark.update(args)
return abort(410, message="Mark {} doesn't exist".format(mark_id))
@auth.login_required
@marshal_with(mark_fields)
def post(self):
post_parser = reqparse.RequestParser()
post_parser.add_argument('type', type=str, required=True,
help='Missing type')
post_parser.add_argument('title', type=str, required=True,
help='Missing title')
post_parser.add_argument('url', type=is_url, required=True)
post_parser.add_argument('tags', type=str)
args = post_parser.parse_args()
return g.user.create_mark(args.type,
args.title,
args.url,
args.tags)
@auth.login_required
@marshal_with(mark_fields)
def delete(self, mark_id):
mark = g.user.get_mark_by_id(mark_id)
if mark:
mark.delete()
return mark
return abort(410, message="Mark {} doesn't exist".format(mark_id))
class Marks(Resource):
@auth.login_required
def get(self, page=1):
get_parser = reqparse.RequestParser()
get_parser.add_argument('q', type=str)
get_parser.add_argument('tag', type=str)
get_parser.add_argument('type', type=str)
get_parser.add_argument('sort', type=str)
args = get_parser.parse_args()
marks = g.user.marks(page,
q=args.q,
type=args.type,
tag=args.tag,
sort=args.sort)
return {'marks': marshal(marks.items, mark_fields),
'pager': g.user.json_pager(marks)}
| {
"repo_name": "plastboks/Flaskmarks-API",
"path": "api/views/mark.py",
"copies": "1",
"size": "3156",
"license": "mit",
"hash": 7584735383102451000,
"line_mean": 31.875,
"line_max": 76,
"alpha_frac": 0.5719264892,
"autogenerated": false,
"ratio": 3.7437722419928825,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4815698731192882,
"avg_score": null,
"num_lines": null
} |
"""API views."""
from django.conf import settings
from rest_framework import decorators, mixins, response, status, viewsets
from rest_framework.views import APIView
from .models import ModoboaInstance, ModoboaExtension
from .forms import ClientVersionForm
from . import constants
from . import models
from . import serializers
# Legacy API, to deprecate
class CurrentVersionView(APIView):
"""Get current modoboa version."""
def get(self, request, fmt=None):
if request.GET.get("client_version") == "1.2.0-rc2":
# Temp. fix
request.GET = request.GET.copy()
request.GET["client_version"] = "1.2.0"
form = ClientVersionForm(request.GET)
if not form.is_valid():
return response.Response(
{"error": (
"Client version and/or site is missing or incorrect")},
status=status.HTTP_400_BAD_REQUEST
)
args = {
"ip_address": request.META.get("REMOTE_ADDR"),
"hostname": form.cleaned_data["client_site"]
}
if ModoboaInstance.objects.filter(**args).exists():
mdinst = ModoboaInstance.objects.get(**args)
elif ModoboaInstance.objects.filter(hostname=args["hostname"]).exists():
mdinst = ModoboaInstance.objects.get(hostname=args["hostname"])
mdinst.ip_address = args["ip_address"]
elif ModoboaInstance.objects.filter(ip_address=args["ip_address"]).exists():
mdinst = ModoboaInstance.objects.get(ip_address=args["ip_address"])
if args["hostname"] not in constants.BAD_HOSTNAME_LIST:
mdinst.hostname = args["hostname"]
elif args["hostname"] not in constants.BAD_HOSTNAME_LIST:
mdinst = ModoboaInstance(**args)
else:
mdinst = None
if mdinst is not None:
if mdinst.known_version != form.cleaned_data["client_version"]:
mdinst.known_version = form.cleaned_data["client_version"]
mdinst.save()
data = {"version": settings.MODOBOA_CURRENT_VERSION[0],
"changelog_url": settings.MODOBOA_CURRENT_VERSION[1]}
return response.Response(data)
class ExtensionListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
"""List all defined extensions."""
queryset = ModoboaExtension.objects.all()
serializer_class = serializers.ModoboaExtensionSerializer
# New API
class InstanceViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin,
viewsets.GenericViewSet):
"""Create or update instance."""
queryset = ModoboaInstance.objects.all()
serializer_class = serializers.InstanceSerializer
@decorators.list_route(methods=["get"])
def search(self, request, *args, **kwargs):
"""Search an instance."""
hostname = request.GET.get("hostname")
if not hostname:
return response.Response({
"error": "No hostname provided."
}, status=status.HTTP_400_BAD_REQUEST)
ip_address = request.META.get("REMOTE_ADDR")
instance = models.ModoboaInstance.objects.filter(
ip_address=ip_address, hostname=hostname).first()
if not instance:
return response.Response({
"error": "Instance not found."
}, status=status.HTTP_404_NOT_FOUND)
serializer = self.get_serializer(instance)
return response.Response(serializer.data)
class VersionViewSet(viewsets.ViewSet):
"""List all versions."""
def list(self, request):
data = []
for extension in models.ModoboaExtension.objects.all():
data.append({
"name": extension.name, "version": extension.version,
"url": ""})
data.append({
"name": "modoboa", "version": settings.MODOBOA_CURRENT_VERSION[0],
"url": settings.MODOBOA_CURRENT_VERSION[1]
})
serializer = serializers.VersionSerializer(data, many=True)
return response.Response(serializer.data)
| {
"repo_name": "tonioo/modoboa-public-api",
"path": "modoboa_public_api/views.py",
"copies": "1",
"size": "4085",
"license": "mit",
"hash": -5763816079134920000,
"line_mean": 36.8240740741,
"line_max": 84,
"alpha_frac": 0.6249694002,
"autogenerated": false,
"ratio": 4.097291875626881,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.522226127582688,
"avg_score": null,
"num_lines": null
} |
# API views
import os
import json
from query import parse_query
from interfaces.flickr import parse_interface_flickr
from django.http import HttpResponse
INTERFACE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/interfaces/json/'
INTERFACES = ["university", "flickr", "weather"];
FLICKR_KEY = ["Yahoo", "pictures", "worthless", "internet"]
WEATHER_KEY = ["rain", "snow", "climate", "Al Gore", "Democrats", "wind", "hail", "hurricane", "hot", "cold"]
COLLEGE_KEY = []
def interface(request, inter, disc="default"):
print "SHIT GOT CALLED {}".format(inter)
if inter.lower() in INTERFACES:
print "WE ARE GOOD TO FUCKING GO"
response = open(INTERFACE_DIR + inter.lower() + '.json').read()
else:
print "FUCKIN {} AINT IN {}".format(inter, INTERFACES)
data = { "status": 1, "key": inter }
response = json.dumps(data, sort_keys=True)
return HttpResponse(response, mimetype='application/json')
def error(request):
response = {"error": "faulty API call"}
return HttpResponse(json.dumps(response), mimetype='application/json')
| {
"repo_name": "bezi/globalizr",
"path": "globalizr/api/views.py",
"copies": "1",
"size": "1088",
"license": "mit",
"hash": -7600003124083859000,
"line_mean": 40.8461538462,
"line_max": 109,
"alpha_frac": 0.6691176471,
"autogenerated": false,
"ratio": 3.296969696969697,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9435864723244239,
"avg_score": 0.006044524165091541,
"num_lines": 26
} |
# api/views/profile.py
from flask import g
from flask.ext.restful import fields, marshal_with, reqparse, abort
from ..core.setup import Resource, auth, config
from ..models import User
from ..core.validators import validate_email
user_fields = {
'id': fields.Integer,
'username': fields.String,
'per_page': fields.Integer,
'email': fields.String,
'created': fields.DateTime
}
def is_email(value):
try:
validate_email(value)
return value
except ValueError as e:
raise ValueError(e)
class Profile(Resource):
@marshal_with(user_fields)
def post(self):
if not config['CAN_REGISTER']:
return abort(405, message="User registration is disabled")
post_parser = reqparse.RequestParser()
post_parser.add_argument('email',
type=is_email,
required=True
)
post_parser.add_argument('password',
type=str,
required=True,
help='Missing password'
)
args = post_parser.parse_args()
u = User(args.email, args.password)
user = u.save()
if user:
return user
return abort(409, message="User with this email {} exists"
.format(args.email))
@auth.login_required
@marshal_with(user_fields)
def get(self):
return g.user
@auth.login_required
@marshal_with(user_fields)
def put(self):
put_parser = reqparse.RequestParser()
put_parser.add_argument('username', type=str)
put_parser.add_argument('email', type=is_email)
put_parser.add_argument('password', type=is_email)
put_parser.add_argument('per_page', type=int)
args = put_parser.parse_args()
return g.user.update(args)
@auth.login_required
@marshal_with(user_fields)
def delete(self):
return g.user.delete()
| {
"repo_name": "plastboks/Flaskmarks-API",
"path": "api/views/profile.py",
"copies": "1",
"size": "2059",
"license": "mit",
"hash": 6053696413204733000,
"line_mean": 28.4142857143,
"line_max": 70,
"alpha_frac": 0.5633802817,
"autogenerated": false,
"ratio": 4.151209677419355,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5214589959119356,
"avg_score": null,
"num_lines": null
} |
# api/views/setting.py
from flask import g
from flask.ext.restful import fields, marshal_with, reqparse, abort
from ..core.setup import Resource, auth
import json
setting_fields = {
'name': fields.String,
'client': fields.String,
'json': fields.String,
'created': fields.DateTime,
'updated': fields.DateTime
}
def is_json(value):
try:
json.dumps(value)
return value
except SyntaxError:
raise "Invalid JSON format"
class Setting(Resource):
@auth.login_required
@marshal_with(setting_fields)
def get(self, name):
setting = g.user.get_setting_by_name(name)
if setting:
return setting
return abort(410, message="Setting {} doesn't exists".format(name))
@auth.login_required
@marshal_with(setting_fields)
def put(self, name):
put_parser = reqparse.RequestParser()
put_parser.add_argument('json', type=is_json, required=True,
help='Missing JSON setting blob')
put_parser.add_argument('client', type=str, required=False)
args = put_parser.parse_args()
setting = g.user.get_setting_by_name(name)
if setting:
return setting.update(args.client, args.json)
return abort(410, message="Setting {} doesn't exist".format(name))
@auth.login_required
@marshal_with(setting_fields)
def post(self):
post_parser = reqparse.RequestParser()
post_parser.add_argument('name', type=str, required=True,
help='Missing name')
post_parser.add_argument('client', type=str, required=False)
post_parser.add_argument('json', type=is_json, required=True,
help='Missing JSON setting blob')
args = post_parser.parse_args()
return g.user.create_setting(args.name, args.client, args.json)
@auth.login_required
@marshal_with(setting_fields)
def delete(self, name):
setting = g.user.get_setting_by_name(name)
if setting:
setting.delete()
return setting
return abort(410, message="Setting {} doesn't exist".format(name))
| {
"repo_name": "plastboks/Flaskmarks-API",
"path": "api/views/setting.py",
"copies": "1",
"size": "2188",
"license": "mit",
"hash": 8721360821436905000,
"line_mean": 31.6567164179,
"line_max": 75,
"alpha_frac": 0.6192870201,
"autogenerated": false,
"ratio": 3.893238434163701,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5012525454263701,
"avg_score": null,
"num_lines": null
} |
# API with users and posts
import hashlib, uuid
import flask_gasket.control
# uses userID as additional salt
# uuid.uuid4().hex
salt = 'df67a20945b34119a39f7bbe37a3697f'
# len(uuid.uuid4().hex)
SIZE_ID = 32
def authorize(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
fullToken = recv['token']
token = fullToken[:SIZE_ID]
userID = fullToken[SIZE_ID:]
user = conn.getPrimary(userID,serverDef)
if user == None:
return (False,flask_gasket.control.errorNotFound)
if 'serverToken' not in user or token != user['serverToken']:
return (False,flask_gasket.control.errorUnauthorized)
if user['userID'] != userID:
return (False,flask_gasket.control.errorUnauthorized)
ret = { 'user': user }
return (True,ret)
def userSend(args):
fromServer = args['_last']
return (True,fromServer)
def postSend(args):
fromServer = args['_last']
return (True,fromServer)
def postSendList(args):
fromServer = args['_last']
return (True,fromServer)
def signup(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
userID = uuid.uuid4().hex
# password
password = recv['password']
hashpass = hashlib.sha256(password + userID + salt).hexdigest()
token = uuid.uuid4().hex
# recv is added to toServer to complete serverDef
toServer = {}
toServer['hashpass'] = hashpass
toServer['serverToken'] = token
toClient = conn.create(userID,recv,toServer,serverDef)
isSuccess = False
if 'code' not in toClient:
toClient['token'] = token + userID
isSuccess = True
return (isSuccess,toClient)
def login(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
# if don't have user, get by userID
if 'userID' not in recv:
ret = conn.getSecondary('username',recv['username'],serverDef)
if len(ret) == 0:
return (False,flask_gasket.control.errorNotFound)
user = ret[0]
userID = user['userID']
else:
userID = recv['userID']
# get raw
user = conn.getPrimary(userID,serverDef)
if user == None:
return (False,flask_gasket.control.errorNotFound)
# check hashpass
password = recv['password']
hashpass = hashlib.sha256(password + userID + salt).hexdigest()
if hashpass != user['hashpass']:
return (False,flask_gasket.control.errorUnauthorized)
token = uuid.uuid4().hex
user['serverToken'] = token
toClient = conn.update(userID,{},user,serverDef,user)
if 'code' not in toClient:
toClient['token'] = token + userID
return (True,toClient)
def logout(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
user = args['_funcs']['authorize']['user']
# remove token
del user['serverToken']
# conn.update
conn.update(user['userID'],{},user,serverDef,user)
# return success
return (True,{})
def getUserByName(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
ret = conn.getSecondary('username',recv['username'],serverDef)
if len(ret) == 0:
return (False,flask_gasket.control.errorNotFound)
toClient = ret[0]
return (True,toClient)
def getUserByID(args):
serverDef = args['_all_models']['user']['_server']
recv = args['_recv']
conn = args['_conn']
ret = conn.getPrimary(recv['userID'],serverDef)
if ret == None:
return (False,flask_gasket.control.errorNotFound)
toClient = ret
return (True,toClient)
def getUserPosts(args):
serverDef = args['_all_models']['post']['_server']
recv = args['_recv']
conn = args['_conn']
ret = conn.getSecondary('userID',recv['userID'],serverDef)
ret = sortVals(ret)
toClient = { 'list':ret }
return (True,toClient)
def createPost(args):
serverUserDef = args['_all_models']['user']['_server']
serverDef = args['_all_models']['post']['_server']
recv = args['_recv']
conn = args['_conn']
user = args['_funcs']['authorize']['user']
toServer = {
'username':user['username'],
'name':user['name'],
'userID':user['userID']
}
postID = uuid.uuid4().hex
toClient = conn.create(postID,recv,toServer,serverDef)
isSuccess = ('code' not in toClient)
return (isSuccess,toClient)
def getPost(args):
serverDef = args['_all_models']['post']['_server']
recv = args['_recv']
conn = args['_conn']
ret = conn.getPrimary(recv['postID'],serverDef)
if ret == None:
return (False,flask_gasket.control.errorNotFound)
toClient = ret
return (True,toClient)
| {
"repo_name": "dbunker/Flask-Gasket",
"path": "example/view.py",
"copies": "1",
"size": "4502",
"license": "bsd-3-clause",
"hash": -1515083914184472800,
"line_mean": 19.9441860465,
"line_max": 64,
"alpha_frac": 0.6674811195,
"autogenerated": false,
"ratio": 2.987392169873922,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7694441609869018,
"avg_score": 0.2920863359009807,
"num_lines": 215
} |
# api wrapper for three.js
__pragma__ ('noanno')
def _ctor(obj):
def _c_(*args):
return __new__(obj (*args))
return _c_
api = __pragma__ ('js',
'{}',
'THREE'
)
WebGLRenderTargetCube = _ctor(api.WebGLRenderTargetCube)
WebGLRenderTarget = _ctor(api.WebGLRenderTarget)
WebGLRenderer = _ctor(api.WebGLRenderer)
ShaderLib = _ctor(api.ShaderLib)
UniformsLib = _ctor(api.UniformsLib)
UniformsUtils = _ctor(api.UniformsUtils)
ShaderChunk = _ctor(api.ShaderChunk)
FogExp2 = _ctor(api.FogExp2)
Fog = _ctor(api.Fog)
Scene = _ctor(api.Scene)
LensFlare = _ctor(api.LensFlare)
Sprite = _ctor(api.Sprite)
LOD = _ctor(api.LOD)
SkinnedMesh = _ctor(api.SkinnedMesh)
Skeleton = _ctor(api.Skeleton)
Bone = _ctor(api.Bone)
Mesh = _ctor(api.Mesh)
LineSegments = _ctor(api.LineSegments)
LineLoop = _ctor(api.LineLoop)
Line = _ctor(api.Line)
Points = _ctor(api.Points)
Group = _ctor(api.Group)
VideoTexture = _ctor(api.VideoTexture)
DataTexture = _ctor(api.DataTexture)
CompressedTexture = _ctor(api.CompressedTexture)
CubeTexture = _ctor(api.CubeTexture)
CanvasTexture = _ctor(api.CanvasTexture)
DepthTexture = _ctor(api.DepthTexture)
Texture = _ctor(api.Texture)
CompressedTextureLoader = _ctor(api.CompressedTextureLoader)
DataTextureLoader = _ctor(api.DataTextureLoader)
CubeTextureLoader = _ctor(api.CubeTextureLoader)
TextureLoader = _ctor(api.TextureLoader)
ObjectLoader = _ctor(api.ObjectLoader)
MaterialLoader = _ctor(api.MaterialLoader)
BufferGeometryLoader = _ctor(api.BufferGeometryLoader)
DefaultLoadingManager = _ctor(api.DefaultLoadingManager)
LoadingManager = _ctor(api.LoadingManager)
JSONLoader = _ctor(api.JSONLoader)
ImageLoader = _ctor(api.ImageLoader)
FontLoader = _ctor(api.FontLoader)
FileLoader = _ctor(api.FileLoader)
Loader = _ctor(api.Loader)
Cache = _ctor(api.Cache)
AudioLoader = _ctor(api.AudioLoader)
SpotLightShadow = _ctor(api.SpotLightShadow)
SpotLight = _ctor(api.SpotLight)
PointLight = _ctor(api.PointLight)
RectAreaLight = _ctor(api.RectAreaLight)
HemisphereLight = _ctor(api.HemisphereLight)
DirectionalLightShadow = _ctor(api.DirectionalLightShadow)
DirectionalLight = _ctor(api.DirectionalLight)
AmbientLight = _ctor(api.AmbientLight)
LightShadow = _ctor(api.LightShadow)
Light = _ctor(api.Light)
StereoCamera = _ctor(api.StereoCamera)
PerspectiveCamera = _ctor(api.PerspectiveCamera)
OrthographicCamera = _ctor(api.OrthographicCamera)
CubeCamera = _ctor(api.CubeCamera)
ArrayCamera = _ctor(api.ArrayCamera)
Camera = _ctor(api.Camera)
AudioListener = _ctor(api.AudioListener)
PositionalAudio = _ctor(api.PositionalAudio)
AudioContext = _ctor(api.AudioContext)
AudioAnalyser = _ctor(api.AudioAnalyser)
Audio = _ctor(api.Audio)
VectorKeyframeTrack = _ctor(api.VectorKeyframeTrack)
StringKeyframeTrack = _ctor(api.StringKeyframeTrack)
QuaternionKeyframeTrack = _ctor(api.QuaternionKeyframeTrack)
NumberKeyframeTrack = _ctor(api.NumberKeyframeTrack)
ColorKeyframeTrack = _ctor(api.ColorKeyframeTrack)
BooleanKeyframeTrack = _ctor(api.BooleanKeyframeTrack)
PropertyMixer = _ctor(api.PropertyMixer)
PropertyBinding = _ctor(api.PropertyBinding)
KeyframeTrack = _ctor(api.KeyframeTrack)
AnimationUtils = _ctor(api.AnimationUtils)
AnimationObjectGroup = _ctor(api.AnimationObjectGroup)
AnimationMixer = _ctor(api.AnimationMixer)
AnimationClip = _ctor(api.AnimationClip)
Uniform = _ctor(api.Uniform)
InstancedBufferGeometry = _ctor(api.InstancedBufferGeometry)
BufferGeometry = _ctor(api.BufferGeometry)
GeometryIdCount = _ctor(api.GeometryIdCount)
Geometry = _ctor(api.Geometry)
InterleavedBufferAttribute = _ctor(api.InterleavedBufferAttribute)
InstancedInterleavedBuffer = _ctor(api.InstancedInterleavedBuffer)
InterleavedBuffer = _ctor(api.InterleavedBuffer)
InstancedBufferAttribute = _ctor(api.InstancedBufferAttribute)
Face3 = _ctor(api.Face3)
Object3D = _ctor(api.Object3D)
Raycaster = _ctor(api.Raycaster)
Layers = _ctor(api.Layers)
EventDispatcher = _ctor(api.EventDispatcher)
Clock = _ctor(api.Clock)
QuaternionLinearInterpolant = _ctor(api.QuaternionLinearInterpolant)
LinearInterpolant = _ctor(api.LinearInterpolant)
DiscreteInterpolant = _ctor(api.DiscreteInterpolant)
CubicInterpolant = _ctor(api.CubicInterpolant)
Interpolant = _ctor(api.Interpolant)
Triangle = _ctor(api.Triangle)
Math = _ctor(api.Math)
Spherical = _ctor(api.Spherical)
Cylindrical = _ctor(api.Cylindrical)
Plane = _ctor(api.Plane)
Frustum = _ctor(api.Frustum)
Sphere = _ctor(api.Sphere)
Ray = _ctor(api.Ray)
Matrix4 = _ctor(api.Matrix4)
Matrix3 = _ctor(api.Matrix3)
Box3 = _ctor(api.Box3)
Box2 = _ctor(api.Box2)
Line3 = _ctor(api.Line3)
Euler = _ctor(api.Euler)
Vector3 = _ctor(api.Vector3)
Quaternion = _ctor(api.Quaternion)
Color = _ctor(api.Color)
MorphBlendMesh = _ctor(api.MorphBlendMesh)
ImmediateRenderObject = _ctor(api.ImmediateRenderObject)
VertexNormalsHelper = _ctor(api.VertexNormalsHelper)
SpotLightHelper = _ctor(api.SpotLightHelper)
SkeletonHelper = _ctor(api.SkeletonHelper)
PointLightHelper = _ctor(api.PointLightHelper)
RectAreaLightHelper = _ctor(api.RectAreaLightHelper)
HemisphereLightHelper = _ctor(api.HemisphereLightHelper)
GridHelper = _ctor(api.GridHelper)
PolarGridHelper = _ctor(api.PolarGridHelper)
FaceNormalsHelper = _ctor(api.FaceNormalsHelper)
DirectionalLightHelper = _ctor(api.DirectionalLightHelper)
CameraHelper = _ctor(api.CameraHelper)
BoxHelper = _ctor(api.BoxHelper)
ArrowHelper = _ctor(api.ArrowHelper)
AxisHelper = _ctor(api.AxisHelper)
CatmullRomCurve3 = _ctor(api.CatmullRomCurve3)
CubicBezierCurve3 = _ctor(api.CubicBezierCurve3)
QuadraticBezierCurve3 = _ctor(api.QuadraticBezierCurve3)
LineCurve3 = _ctor(api.LineCurve3)
ArcCurve = _ctor(api.ArcCurve)
EllipseCurve = _ctor(api.EllipseCurve)
SplineCurve = _ctor(api.SplineCurve)
CubicBezierCurve = _ctor(api.CubicBezierCurve)
QuadraticBezierCurve = _ctor(api.QuadraticBezierCurve)
LineCurve = _ctor(api.LineCurve)
Shape = _ctor(api.Shape)
Path = _ctor(api.Path)
ShapePath = _ctor(api.ShapePath)
Font = _ctor(api.Font)
CurvePath = _ctor(api.CurvePath)
Curve = _ctor(api.Curve)
ShapeUtils = _ctor(api.ShapeUtils)
SceneUtils = _ctor(api.SceneUtils)
WireframeGeometry = _ctor(api.WireframeGeometry)
ParametricGeometry = _ctor(api.ParametricGeometry)
ParametricBufferGeometry = _ctor(api.ParametricBufferGeometry)
TetrahedronGeometry = _ctor(api.TetrahedronGeometry)
TetrahedronBufferGeometry = _ctor(api.TetrahedronBufferGeometry)
OctahedronGeometry = _ctor(api.OctahedronGeometry)
OctahedronBufferGeometry = _ctor(api.OctahedronBufferGeometry)
IcosahedronGeometry = _ctor(api.IcosahedronGeometry)
IcosahedronBufferGeometry = _ctor(api.IcosahedronBufferGeometry)
DodecahedronGeometry = _ctor(api.DodecahedronGeometry)
DodecahedronBufferGeometry = _ctor(api.DodecahedronBufferGeometry)
PolyhedronGeometry = _ctor(api.PolyhedronGeometry)
PolyhedronBufferGeometry = _ctor(api.PolyhedronBufferGeometry)
TubeGeometry = _ctor(api.TubeGeometry)
TubeBufferGeometry = _ctor(api.TubeBufferGeometry)
TorusKnotGeometry = _ctor(api.TorusKnotGeometry)
TorusKnotBufferGeometry = _ctor(api.TorusKnotBufferGeometry)
TorusGeometry = _ctor(api.TorusGeometry)
TorusBufferGeometry = _ctor(api.TorusBufferGeometry)
TextGeometry = _ctor(api.TextGeometry)
TextBufferGeometry = _ctor(api.TextBufferGeometry)
SphereGeometry = _ctor(api.SphereGeometry)
SphereBufferGeometry = _ctor(api.SphereBufferGeometry)
RingGeometry = _ctor(api.RingGeometry)
RingBufferGeometry = _ctor(api.RingBufferGeometry)
PlaneGeometry = _ctor(api.PlaneGeometry)
PlaneBufferGeometry = _ctor(api.PlaneBufferGeometry)
LatheGeometry = _ctor(api.LatheGeometry)
LatheBufferGeometry = _ctor(api.LatheBufferGeometry)
ShapeGeometry = _ctor(api.ShapeGeometry)
ShapeBufferGeometry = _ctor(api.ShapeBufferGeometry)
ExtrudeGeometry = _ctor(api.ExtrudeGeometry)
ExtrudeBufferGeometry = _ctor(api.ExtrudeBufferGeometry)
EdgesGeometry = _ctor(api.EdgesGeometry)
ConeGeometry = _ctor(api.ConeGeometry)
ConeBufferGeometry = _ctor(api.ConeBufferGeometry)
CylinderGeometry = _ctor(api.CylinderGeometry)
CylinderBufferGeometry = _ctor(api.CylinderBufferGeometry)
CircleGeometry = _ctor(api.CircleGeometry)
CircleBufferGeometry = _ctor(api.CircleBufferGeometry)
BoxGeometry = _ctor(api.BoxGeometry)
BoxBufferGeometry = _ctor(api.BoxBufferGeometry)
ShadowMaterial = _ctor(api.ShadowMaterial)
SpriteMaterial = _ctor(api.SpriteMaterial)
RawShaderMaterial = _ctor(api.RawShaderMaterial)
ShaderMaterial = _ctor(api.ShaderMaterial)
PointsMaterial = _ctor(api.PointsMaterial)
MeshPhysicalMaterial = _ctor(api.MeshPhysicalMaterial)
MeshStandardMaterial = _ctor(api.MeshStandardMaterial)
MeshPhongMaterial = _ctor(api.MeshPhongMaterial)
MeshToonMaterial = _ctor(api.MeshToonMaterial)
MeshNormalMaterial = _ctor(api.MeshNormalMaterial)
MeshLambertMaterial = _ctor(api.MeshLambertMaterial)
MeshDepthMaterial = _ctor(api.MeshDepthMaterial)
MeshBasicMaterial = _ctor(api.MeshBasicMaterial)
LineDashedMaterial = _ctor(api.LineDashedMaterial)
LineBasicMaterial = _ctor(api.LineBasicMaterial)
Material = _ctor(api.Material)
Float64BufferAttribute = _ctor(api.Float64BufferAttribute)
Float32BufferAttribute = _ctor(api.Float32BufferAttribute)
Uint32BufferAttribute = _ctor(api.Uint32BufferAttribute)
Int32BufferAttribute = _ctor(api.Int32BufferAttribute)
Uint16BufferAttribute = _ctor(api.Uint16BufferAttribute)
Int16BufferAttribute = _ctor(api.Int16BufferAttribute)
Uint8ClampedBufferAttribute = _ctor(api.Uint8ClampedBufferAttribute)
Uint8BufferAttribute = _ctor(api.Uint8BufferAttribute)
Int8BufferAttribute = _ctor(api.Int8BufferAttribute)
BufferAttribute = _ctor(api.BufferAttribute)
REVISION = _ctor(api.REVISION)
MOUSE = _ctor(api.MOUSE)
CullFaceNone = _ctor(api.CullFaceNone)
CullFaceBack = _ctor(api.CullFaceBack)
CullFaceFront = _ctor(api.CullFaceFront)
CullFaceFrontBack = _ctor(api.CullFaceFrontBack)
FrontFaceDirectionCW = _ctor(api.FrontFaceDirectionCW)
FrontFaceDirectionCCW = _ctor(api.FrontFaceDirectionCCW)
BasicShadowMap = _ctor(api.BasicShadowMap)
PCFShadowMap = _ctor(api.PCFShadowMap)
PCFSoftShadowMap = _ctor(api.PCFSoftShadowMap)
FrontSide = _ctor(api.FrontSide)
BackSide = _ctor(api.BackSide)
DoubleSide = _ctor(api.DoubleSide)
FlatShading = _ctor(api.FlatShading)
SmoothShading = _ctor(api.SmoothShading)
NoColors = _ctor(api.NoColors)
FaceColors = _ctor(api.FaceColors)
VertexColors = _ctor(api.VertexColors)
NoBlending = _ctor(api.NoBlending)
NormalBlending = _ctor(api.NormalBlending)
AdditiveBlending = _ctor(api.AdditiveBlending)
SubtractiveBlending = _ctor(api.SubtractiveBlending)
MultiplyBlending = _ctor(api.MultiplyBlending)
CustomBlending = _ctor(api.CustomBlending)
AddEquation = _ctor(api.AddEquation)
SubtractEquation = _ctor(api.SubtractEquation)
ReverseSubtractEquation = _ctor(api.ReverseSubtractEquation)
MinEquation = _ctor(api.MinEquation)
MaxEquation = _ctor(api.MaxEquation)
ZeroFactor = _ctor(api.ZeroFactor)
OneFactor = _ctor(api.OneFactor)
SrcColorFactor = _ctor(api.SrcColorFactor)
OneMinusSrcColorFactor = _ctor(api.OneMinusSrcColorFactor)
SrcAlphaFactor = _ctor(api.SrcAlphaFactor)
OneMinusSrcAlphaFactor = _ctor(api.OneMinusSrcAlphaFactor)
DstAlphaFactor = _ctor(api.DstAlphaFactor)
OneMinusDstAlphaFactor = _ctor(api.OneMinusDstAlphaFactor)
DstColorFactor = _ctor(api.DstColorFactor)
OneMinusDstColorFactor = _ctor(api.OneMinusDstColorFactor)
SrcAlphaSaturateFactor = _ctor(api.SrcAlphaSaturateFactor)
NeverDepth = _ctor(api.NeverDepth)
AlwaysDepth = _ctor(api.AlwaysDepth)
LessDepth = _ctor(api.LessDepth)
LessEqualDepth = _ctor(api.LessEqualDepth)
EqualDepth = _ctor(api.EqualDepth)
GreaterEqualDepth = _ctor(api.GreaterEqualDepth)
GreaterDepth = _ctor(api.GreaterDepth)
NotEqualDepth = _ctor(api.NotEqualDepth)
MultiplyOperation = _ctor(api.MultiplyOperation)
MixOperation = _ctor(api.MixOperation)
AddOperation = _ctor(api.AddOperation)
NoToneMapping = _ctor(api.NoToneMapping)
LinearToneMapping = _ctor(api.LinearToneMapping)
ReinhardToneMapping = _ctor(api.ReinhardToneMapping)
Uncharted2ToneMapping = _ctor(api.Uncharted2ToneMapping)
CineonToneMapping = _ctor(api.CineonToneMapping)
UVMapping = _ctor(api.UVMapping)
CubeReflectionMapping = _ctor(api.CubeReflectionMapping)
CubeRefractionMapping = _ctor(api.CubeRefractionMapping)
EquirectangularReflectionMapping = _ctor(api.EquirectangularReflectionMapping)
EquirectangularRefractionMapping = _ctor(api.EquirectangularRefractionMapping)
SphericalReflectionMapping = _ctor(api.SphericalReflectionMapping)
CubeUVReflectionMapping = _ctor(api.CubeUVReflectionMapping)
CubeUVRefractionMapping = _ctor(api.CubeUVRefractionMapping)
RepeatWrapping = _ctor(api.RepeatWrapping)
ClampToEdgeWrapping = _ctor(api.ClampToEdgeWrapping)
MirroredRepeatWrapping = _ctor(api.MirroredRepeatWrapping)
NearestFilter = _ctor(api.NearestFilter)
NearestMipMapNearestFilter = _ctor(api.NearestMipMapNearestFilter)
NearestMipMapLinearFilter = _ctor(api.NearestMipMapLinearFilter)
LinearFilter = _ctor(api.LinearFilter)
LinearMipMapNearestFilter = _ctor(api.LinearMipMapNearestFilter)
LinearMipMapLinearFilter = _ctor(api.LinearMipMapLinearFilter)
UnsignedByteType = _ctor(api.UnsignedByteType)
ByteType = _ctor(api.ByteType)
ShortType = _ctor(api.ShortType)
UnsignedShortType = _ctor(api.UnsignedShortType)
IntType = _ctor(api.IntType)
UnsignedIntType = _ctor(api.UnsignedIntType)
FloatType = _ctor(api.FloatType)
HalfFloatType = _ctor(api.HalfFloatType)
UnsignedShort4444Type = _ctor(api.UnsignedShort4444Type)
UnsignedShort5551Type = _ctor(api.UnsignedShort5551Type)
UnsignedShort565Type = _ctor(api.UnsignedShort565Type)
UnsignedInt248Type = _ctor(api.UnsignedInt248Type)
AlphaFormat = _ctor(api.AlphaFormat)
RGBFormat = _ctor(api.RGBFormat)
RGBAFormat = _ctor(api.RGBAFormat)
LuminanceFormat = _ctor(api.LuminanceFormat)
LuminanceAlphaFormat = _ctor(api.LuminanceAlphaFormat)
RGBEFormat = _ctor(api.RGBEFormat)
DepthFormat = _ctor(api.DepthFormat)
DepthStencilFormat = _ctor(api.DepthStencilFormat)
RGB_S3TC_DXT1_Format = _ctor(api.RGB_S3TC_DXT1_Format)
RGBA_S3TC_DXT1_Format = _ctor(api.RGBA_S3TC_DXT1_Format)
RGBA_S3TC_DXT3_Format = _ctor(api.RGBA_S3TC_DXT3_Format)
RGBA_S3TC_DXT5_Format = _ctor(api.RGBA_S3TC_DXT5_Format)
RGB_PVRTC_4BPPV1_Format = _ctor(api.RGB_PVRTC_4BPPV1_Format)
RGB_PVRTC_2BPPV1_Format = _ctor(api.RGB_PVRTC_2BPPV1_Format)
RGBA_PVRTC_4BPPV1_Format = _ctor(api.RGBA_PVRTC_4BPPV1_Format)
RGBA_PVRTC_2BPPV1_Format = _ctor(api.RGBA_PVRTC_2BPPV1_Format)
RGB_ETC1_Format = _ctor(api.RGB_ETC1_Format)
LoopOnce = _ctor(api.LoopOnce)
LoopRepeat = _ctor(api.LoopRepeat)
LoopPingPong = _ctor(api.LoopPingPong)
InterpolateDiscrete = _ctor(api.InterpolateDiscrete)
InterpolateLinear = _ctor(api.InterpolateLinear)
InterpolateSmooth = _ctor(api.InterpolateSmooth)
ZeroCurvatureEnding = _ctor(api.ZeroCurvatureEnding)
ZeroSlopeEnding = _ctor(api.ZeroSlopeEnding)
WrapAroundEnding = _ctor(api.WrapAroundEnding)
TrianglesDrawMode = _ctor(api.TrianglesDrawMode)
TriangleStripDrawMode = _ctor(api.TriangleStripDrawMode)
TriangleFanDrawMode = _ctor(api.TriangleFanDrawMode)
LinearEncoding = _ctor(api.LinearEncoding)
sRGBEncoding = _ctor(api.sRGBEncoding)
GammaEncoding = _ctor(api.GammaEncoding)
RGBEEncoding = _ctor(api.RGBEEncoding)
LogLuvEncoding = _ctor(api.LogLuvEncoding)
RGBM7Encoding = _ctor(api.RGBM7Encoding)
RGBM16Encoding = _ctor(api.RGBM16Encoding)
RGBDEncoding = _ctor(api.RGBDEncoding)
BasicDepthPacking = _ctor(api.BasicDepthPacking)
RGBADepthPacking = _ctor(api.RGBADepthPacking)
CubeGeometry = _ctor(api.CubeGeometry)
Face4 = _ctor(api.Face4)
LineStrip = _ctor(api.LineStrip)
LinePieces = _ctor(api.LinePieces)
MeshFaceMaterial = _ctor(api.MeshFaceMaterial)
MultiMaterial = _ctor(api.MultiMaterial)
PointCloud = _ctor(api.PointCloud)
Particle = _ctor(api.Particle)
ParticleSystem = _ctor(api.ParticleSystem)
PointCloudMaterial = _ctor(api.PointCloudMaterial)
ParticleBasicMaterial = _ctor(api.ParticleBasicMaterial)
ParticleSystemMaterial = _ctor(api.ParticleSystemMaterial)
Vertex = _ctor(api.Vertex)
DynamicBufferAttribute = _ctor(api.DynamicBufferAttribute)
Int8Attribute = _ctor(api.Int8Attribute)
Uint8Attribute = _ctor(api.Uint8Attribute)
Uint8ClampedAttribute = _ctor(api.Uint8ClampedAttribute)
Int16Attribute = _ctor(api.Int16Attribute)
Uint16Attribute = _ctor(api.Uint16Attribute)
Int32Attribute = _ctor(api.Int32Attribute)
Uint32Attribute = _ctor(api.Uint32Attribute)
Float32Attribute = _ctor(api.Float32Attribute)
Float64Attribute = _ctor(api.Float64Attribute)
ClosedSplineCurve3 = _ctor(api.ClosedSplineCurve3)
SplineCurve3 = _ctor(api.SplineCurve3)
Spline = _ctor(api.Spline)
BoundingBoxHelper = _ctor(api.BoundingBoxHelper)
EdgesHelper = _ctor(api.EdgesHelper)
WireframeHelper = _ctor(api.WireframeHelper)
XHRLoader = _ctor(api.XHRLoader)
BinaryTextureLoader = _ctor(api.BinaryTextureLoader)
GeometryUtils = _ctor(api.GeometryUtils)
ImageUtils = _ctor(api.ImageUtils)
Projector = _ctor(api.Projector)
CanvasRenderer = _ctor(api.CanvasRenderer)
| {
"repo_name": "QQuick/Transcrypt",
"path": "transcrypt/demos/pysteroids_demo/org/threejs/__init__.py",
"copies": "1",
"size": "17190",
"license": "apache-2.0",
"hash": 3954658747400767000,
"line_mean": 41.8520408163,
"line_max": 78,
"alpha_frac": 0.792495637,
"autogenerated": false,
"ratio": 2.8479125248508947,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9124968183298932,
"avg_score": 0.0030879957103924953,
"num_lines": 392
} |
"""APL 2.0 code from github.com/pkmital/tensorflow_tutorials w/ permission
from Parag K. Mital.
"""
import math
import tensorflow as tf
from tensorflow.python import control_flow_ops
def batch_norm(x, phase_train, scope='bn', affine=True):
"""
Batch normalization on convolutional maps.
from: https://stackoverflow.com/questions/33949786/how-could-i-
use-batch-normalization-in-tensorflow
Only modified to infer shape from input tensor x.
Parameters
----------
x
Tensor, 4D BHWD input maps
phase_train
boolean tf.Variable, true indicates training phase
scope
string, variable scope
affine
whether to affine-transform outputs
Return
------
normed
batch-normalized maps
"""
with tf.variable_scope(scope):
og_shape = x.get_shape().as_list()
if len(og_shape) == 2:
x = tf.reshape(x, [-1, 1, 1, og_shape[1]])
shape = x.get_shape().as_list()
beta = tf.Variable(tf.constant(0.0, shape=[shape[-1]]),
name='beta', trainable=True)
gamma = tf.Variable(tf.constant(1.0, shape=[shape[-1]]),
name='gamma', trainable=affine)
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=0.9)
ema_apply_op = ema.apply([batch_mean, batch_var])
ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)
def mean_var_with_update():
"""Summary
Returns
-------
name : TYPE
Description
"""
with tf.control_dependencies([ema_apply_op]):
return tf.identity(batch_mean), tf.identity(batch_var)
mean, var = control_flow_ops.cond(phase_train,
mean_var_with_update,
lambda: (ema_mean, ema_var))
normed = tf.nn.batch_norm_with_global_normalization(
x, mean, var, beta, gamma, 1e-3, affine)
if len(og_shape) == 2:
normed = tf.reshape(normed, [-1, og_shape[-1]])
return normed
def lrelu(x, leak=0.2, name="lrelu"):
"""Leaky rectifier.
Parameters
----------
x : Tensor
The tensor to apply the nonlinearity to.
leak : float, optional
Leakage parameter.
name : str, optional
Variable scope to use.
Returns
-------
x : Tensor
Output of the nonlinearity.
"""
with tf.variable_scope(name):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
def linear(x, n_units, scope=None, stddev=0.02,
activation=lambda x: x):
"""Fully-connected network.
Parameters
----------
x : Tensor
Input tensor to the network.
n_units : int
Number of units to connect to.
scope : str, optional
Variable scope to use.
stddev : float, optional
Initialization's standard deviation.
activation : arguments, optional
Function which applies a nonlinearity
Returns
-------
x : Tensor
Fully-connected output.
"""
shape = x.get_shape().as_list()
with tf.variable_scope(scope or "Linear"):
matrix = tf.get_variable("Matrix", [shape[1], n_units], tf.float32,
tf.random_normal_initializer(stddev=stddev))
return activation(tf.matmul(x, matrix))
| {
"repo_name": "hpssjellis/forth-tensorflow",
"path": "tensorflow-tutorials/libs/connections.py",
"copies": "2",
"size": "3521",
"license": "mit",
"hash": -7156250542624844000,
"line_mean": 30.7207207207,
"line_max": 77,
"alpha_frac": 0.5609201931,
"autogenerated": false,
"ratio": 3.8188720173535793,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 111
} |
"""APL 2.0 code from github.com/pkmital/tensorflow_tutorials w/ permission
from Parag K. Mital.
"""
import math
import tensorflow as tf
def batch_norm(x, phase_train, scope='bn', affine=True):
"""
Batch normalization on convolutional maps.
from: https://stackoverflow.com/questions/33949786/how-could-i-
use-batch-normalization-in-tensorflow
Only modified to infer shape from input tensor x.
Parameters
----------
x
Tensor, 4D BHWD input maps
phase_train
boolean tf.Variable, true indicates training phase
scope
string, variable scope
affine
whether to affine-transform outputs
Return
------
normed
batch-normalized maps
"""
with tf.variable_scope(scope):
og_shape = x.get_shape().as_list()
if len(og_shape) == 2:
x = tf.reshape(x, [-1, 1, 1, og_shape[1]])
shape = x.get_shape().as_list()
beta = tf.Variable(tf.constant(0.0, shape=[shape[-1]]),
name='beta', trainable=True)
gamma = tf.Variable(tf.constant(1.0, shape=[shape[-1]]),
name='gamma', trainable=affine)
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')
ema = tf.train.ExponentialMovingAverage(decay=0.9)
ema_apply_op = ema.apply([batch_mean, batch_var])
ema_mean, ema_var = ema.average(batch_mean), ema.average(batch_var)
def mean_var_with_update():
"""Summary
Returns
-------
name : TYPE
Description
"""
with tf.control_dependencies([ema_apply_op]):
return tf.identity(batch_mean), tf.identity(batch_var)
mean, var = tf.cond(phase_train,
mean_var_with_update,
lambda: (ema_mean, ema_var))
normed = tf.nn.batch_norm_with_global_normalization(
x, mean, var, beta, gamma, 1e-3, affine)
if len(og_shape) == 2:
normed = tf.reshape(normed, [-1, og_shape[-1]])
return normed
def lrelu(x, leak=0.2, name="lrelu"):
"""Leaky rectifier.
Parameters
----------
x : Tensor
The tensor to apply the nonlinearity to.
leak : float, optional
Leakage parameter.
name : str, optional
Variable scope to use.
Returns
-------
x : Tensor
Output of the nonlinearity.
"""
with tf.variable_scope(name):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * abs(x)
def linear(x, n_units, scope=None, stddev=0.02,
activation=lambda x: x):
"""Fully-connected network.
Parameters
----------
x : Tensor
Input tensor to the network.
n_units : int
Number of units to connect to.
scope : str, optional
Variable scope to use.
stddev : float, optional
Initialization's standard deviation.
activation : arguments, optional
Function which applies a nonlinearity
Returns
-------
x : Tensor
Fully-connected output.
"""
shape = x.get_shape().as_list()
with tf.variable_scope(scope or "Linear"):
matrix = tf.get_variable("Matrix", [shape[1], n_units], tf.float32,
tf.random_normal_initializer(stddev=stddev))
return activation(tf.matmul(x, matrix))
def conv2d(x, n_filters,
k_h=5, k_w=5,
stride_h=2, stride_w=2,
stddev=0.02,
activation=None,
bias=True,
padding='SAME',
name="Conv2D"):
"""2D Convolution with options for kernel size, stride, and init deviation.
Parameters
----------
x : Tensor
Input tensor to convolve.
n_filters : int
Number of filters to apply.
k_h : int, optional
Kernel height.
k_w : int, optional
Kernel width.
stride_h : int, optional
Stride in rows.
stride_w : int, optional
Stride in cols.
stddev : float, optional
Initialization's standard deviation.
activation : arguments, optional
Function which applies a nonlinearity
padding : str, optional
'SAME' or 'VALID'
name : str, optional
Variable scope to use.
Returns
-------
x : Tensor
Convolved input.
"""
with tf.variable_scope(name):
w = tf.get_variable(
'w', [k_h, k_w, x.get_shape()[-1], n_filters],
initializer=tf.truncated_normal_initializer(stddev=stddev))
conv = tf.nn.conv2d(
x, w, strides=[1, stride_h, stride_w, 1], padding=padding)
if bias:
b = tf.get_variable(
'b', [n_filters],
initializer=tf.truncated_normal_initializer(stddev=stddev))
conv = tf.nn.bias_add(conv, b)
if activation:
conv = activation(conv)
return conv
| {
"repo_name": "apoorva-sharma/deep-frame-interpolation",
"path": "tensorflow_tutorials-master/python/libs/connections.py",
"copies": "3",
"size": "5006",
"license": "mit",
"hash": -5773513209197408000,
"line_mean": 29.5243902439,
"line_max": 79,
"alpha_frac": 0.5511386336,
"autogenerated": false,
"ratio": 3.850769230769231,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5901907864369231,
"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.