def test_custom_api_serializer(self): """Confirm that an Api can use a custom serializer""" # Origin: https://github.com/django-tastypie/django-tastypie/pull/817 class JSONSerializer(Serializer): formats = ('json', ) api = Api(serializer_class=JSONSerializer) api.register(NoteResource()) request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['content-type'], 'application/json', msg="Expected application/json response but received %s" % resp['content-type']) request = HttpRequest() request.META = {'HTTP_ACCEPT': 'application/xml'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['content-type'], 'application/json', msg="Expected application/json response but received %s" % resp['content-type'])
def test_top_level_include_schema_content(self): api = Api() note_resource = NoteResource() user_resource = UserResource() api.register(note_resource) api.register(user_resource) request = HttpRequest() request.GET = {'fullschema': 'true'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) content = json.loads(resp.content.decode('utf-8')) content['notes']['schema'] = adjust_schema(content['notes']['schema']) content['users']['schema'] = adjust_schema(content['users']['schema']) dummy_request = HttpRequest() dummy_request.method = 'GET' notes_schema = adjust_schema(json.loads(note_resource.get_schema(dummy_request).content.decode('utf-8'))) user_schema = adjust_schema(json.loads(user_resource.get_schema(dummy_request).content.decode('utf-8'))) self.assertEqual(content['notes']['list_endpoint'], '/api/v1/notes/') self.assertEqual(content['notes']['schema'], notes_schema) self.assertEqual(content['users']['list_endpoint'], '/api/v1/users/') self.assertEqual(content['users']['schema'], user_schema)
def test_top_level_jsonp(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() request.META = {"HTTP_ACCEPT": "text/javascript"} request.GET = {"callback": "foo"} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp["content-type"].split(";")[0], "text/javascript") self.assertEqual( resp.content.decode("utf-8"), 'foo({"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}})', ) request = HttpRequest() request.META = {"HTTP_ACCEPT": "text/javascript"} request.GET = {"callback": ""} try: resp = api.top_level(request) self.fail("Broken callback didn't fail!") except BadRequest: # Regression: We expect this, which is fine, but this used to # be an import error. pass
def get_urls(version=1): api = Api(api_name='auth') if version == 1: api.register(User()) return api.urls
def test_top_level_include_schema_content(self): api = Api() note_resource = NoteResource() user_resource = UserResource() api.register(note_resource) api.register(user_resource) request = HttpRequest() request.GET = {"fullschema": "true"} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) content = json.loads(resp.content.decode("utf-8")) content["notes"]["schema"] = adjust_schema(content["notes"]["schema"]) content["users"]["schema"] = adjust_schema(content["users"]["schema"]) dummy_request = HttpRequest() dummy_request.method = "GET" notes_schema = adjust_schema(json.loads(note_resource.get_schema(dummy_request).content.decode("utf-8"))) user_schema = adjust_schema(json.loads(user_resource.get_schema(dummy_request).content.decode("utf-8"))) self.assertEqual(content["notes"]["list_endpoint"], "/api/v1/notes/") self.assertEqual(content["notes"]["schema"], notes_schema) self.assertEqual(content["users"]["list_endpoint"], "/api/v1/users/") self.assertEqual(content["users"]["schema"], user_schema)
def get_urls(version=1): api = Api(api_name='common') if version == 1: api.register(Country()) return api.urls
def named_api(api_name): """ api_name is the version part of the api path """ new_api = Api(api_name=api_name) for resource in resources.__all__: new_api.register(getattr(resources, resource)()) return new_api
def get_api(): # create the naespaces for the applications api = Api(api_name='simpleapp') api.register(TypeResource()) api.register(ProductResource()) base_path_regex = r'^api/v1/' return base_path_regex,api
def test_top_level(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content.decode('utf-8'), '{"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}}')
def test_top_level(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.content, '{"notes": "/api/v1/notes/", "users": "/api/v1/users/"}')
def build_api_urls(): v1_api = Api(api_name='v1') v1_api.register(VideoResource()) v1_api.register(CategoryResource()) return patterns( 'richard.videos.views', (r'^api/', include(v1_api.urls)), )
def resouce_autodiscover(api_name="v1", api_module_name="api"): api = Api(api_name=api_name) for app in settings.INSTALLED_APPS: try: resorce_api = import_module('%s.%s' % (app, api_module_name)) for resource_klass_name in resorce_api.__all__: resource_klass = getattr(resorce_api, resource_klass_name) api.register(resource_klass()) except: continue return api
def test_jsonp_not_on_by_default(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} request.GET = {'callback': 'foo'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['content-type'].split(';')[0], 'application/json') self.assertFalse("foo" in resp.content.decode('utf-8'))
def resouce_autodiscover(): from django.conf import settings from django.utils.importlib import import_module v1_api = Api(api_name='v1') for app in settings.INSTALLED_APPS: try: resorce_api = import_module('%s.api' % app) for resource_klass_name in resorce_api.__all__: resource_klass = getattr(resorce_api, resource_klass_name) v1_api.register(resource_klass()) except: continue return v1_api
def test_top_level_jsonp(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() request.META = {"HTTP_ACCEPT": "text/javascript"} request.GET = {"callback": "foo"} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp["content-type"].split(";")[0], "text/javascript") self.assertEqual( resp.content, 'foo({"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}})', )
def api_factory(): API_VERSION = 'v1' pootle_api = Api(api_name=API_VERSION) pootle_api.register(LanguageResource()) pootle_api.register(ProjectResource()) pootle_api.register(TranslationProjectResource()) return pootle_api
def __init__(self, resources): self.tastypieApi = TastypieApi(api_name='resources') self.dummy_resources = [] self.resources = {} for resource_class in resources: resource = resource_class() self.resources[resource._meta.resource_name] = resource self.tastypieApi.register(resource)
def test_global_registry(self): tastypie.available_apis = {} api = Api() self.assertEqual(len(api._registry), 0) self.assertEqual(len(tastypie.available_apis), 0) api.register(NoteResource()) self.assertEqual(len(api._registry), 1) self.assertEqual(sorted(api._registry.keys()), ["notes"]) self.assertEqual(len(tastypie.available_apis), 1) self.assertEqual(tastypie.available_apis["v1"]["class"], api) self.assertEqual(tastypie.available_apis["v1"]["resources"], ["notes"]) self.assertEqual(tastypie.available_apis["v1"]["representations"], {"NoteRepresentation": "notes"}) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(tastypie.available_apis), 1) self.assertEqual(tastypie.available_apis["v1"]["class"], api) self.assertEqual(tastypie.available_apis["v1"]["resources"], ["notes", "users"]) self.assertEqual( tastypie.available_apis["v1"]["representations"], {"UserRepresentation": "users", "NoteRepresentation": "notes"}, ) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(tastypie.available_apis), 1) self.assertEqual(tastypie.available_apis["v1"]["class"], api) self.assertEqual(tastypie.available_apis["v1"]["resources"], ["notes", "users"]) self.assertEqual( tastypie.available_apis["v1"]["representations"], {"UserRepresentation": "users", "NoteRepresentation": "notes"}, ) self.assertEqual(len(api._canonicals), 2) api.register(UserResource(), canonical=False) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(api._canonicals), 2) self.assertEqual(len(tastypie.available_apis), 1) self.assertEqual(tastypie.available_apis["v1"]["class"], api) self.assertEqual(tastypie.available_apis["v1"]["resources"], ["notes", "users"]) self.assertEqual( tastypie.available_apis["v1"]["representations"], {"UserRepresentation": "users", "NoteRepresentation": "notes"}, )
class Api: def __init__(self, resources): self.tastypieApi = TastypieApi(api_name='resources') self.dummy_resources = [] self.resources = {} for resource_class in resources: resource = resource_class() self.resources[resource._meta.resource_name] = resource self.tastypieApi.register(resource) @property def urls(self): from django.conf.urls.defaults import url, patterns from dummy import DummyResource pattern_list = [] for resource_name, resource in self.resources.items(): if resource_name in self.dummy_resources: pattern_list.append( (r"^resources/%s/(\d*)/?$" % resource_name, DummyResource.get_view(resource))) urls = patterns("",*pattern_list) urls += self.tastypieApi.urls return urls def get_resource_list_uri(self, resource_name): return self.resources[resource_name].get_resource_list_uri() def get_resource_example_data(self, resource_name, method): return self.resources[resource_name].get_example_data(method) def resource_allows_method(self, resource_name, method): return method.lower() in self.resources[resource_name]._meta.allowed_methods def dehydrate(self,request, resource_name, obj): resource = self.resources[resource_name] bundle = resource.build_bundle(obj=obj, request=request) bundle = resource.full_dehydrate(bundle) return bundle.data
def test_canonical_resource_for(self): tastypie.available_apis = {} api = Api() note_resource = NoteResource() user_resource = UserResource() api.register(note_resource) api.register(user_resource) self.assertEqual(len(api._canonicals), 2) self.assertEqual(isinstance(api.canonical_resource_for("notes"), NoteResource), True) api_2 = Api() self.assertRaises(URLReverseError, tastypie._get_canonical_resource_name, api_2, NoteRepresentation) self.assertEqual(tastypie._get_canonical_resource_name(api.api_name, NoteRepresentation), "notes") self.assertEqual(tastypie._get_canonical_resource_name(api.api_name, NoteRepresentation()), "notes") self.assertEqual( tastypie._get_canonical_resource_name(api.api_name, note_resource.detail_representation), "notes" ) self.assertEqual(tastypie._get_canonical_resource_name(api.api_name, UserRepresentation), "users") self.assertEqual(tastypie._get_canonical_resource_name(api.api_name, UserRepresentation()), "users") self.assertEqual( tastypie._get_canonical_resource_name(api.api_name, user_resource.detail_representation), "users" ) api.unregister(user_resource.resource_name) self.assertRaises(NotRegistered, api.canonical_resource_for, "users")
def test_top_level_jsonp(self): api = Api() api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} request.GET = {'callback': 'foo'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['content-type'].split(';')[0], 'text/javascript') self.assertEqual(resp.content, 'foo({"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}})') request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} request.GET = {'callback': ''} try: resp = api.top_level(request) self.fail("Broken callback didn't fail!") except BadRequest: # Regression: We expect this, which is fine, but this used to # be an import error. pass
def test_register(self): api = Api() self.assertEqual(len(api._registry), 0) api.register(NoteResource()) self.assertEqual(len(api._registry), 1) self.assertEqual(sorted(api._registry.keys()), ["notes"]) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(api._canonicals), 2) api.register(UserResource(), canonical=False) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(api._canonicals), 2)
def test_global_registry(self): api = Api() self.assertEqual(len(api._registry), 0) api.register(NoteResource()) self.assertEqual(len(api._registry), 1) self.assertEqual(sorted(api._registry.keys()), ['notes']) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) self.assertEqual(len(api._canonicals), 2) api.register(UserResource(), canonical=False) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) self.assertEqual(len(api._canonicals), 2)
def test_canonical_resource_for(self): api = Api() note_resource = NoteResource() user_resource = UserResource() api.register(note_resource) api.register(user_resource) self.assertEqual(len(api._canonicals), 2) self.assertEqual(isinstance(api.canonical_resource_for('notes'), NoteResource), True) api.unregister(user_resource._meta.resource_name) self.assertRaises(NotRegistered, api.canonical_resource_for, 'users')
def test_register(self): # NOTE: these have all been registered in core.tests.api_urls api = Api() self.assertEqual(len(api._registry), 0) api.register(NoteResource()) self.assertEqual(len(api._registry), 1) self.assertEqual(sorted(api._registry.keys()), ['notes']) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) self.assertEqual(len(api._canonicals), 2) api.register(UserResource(), canonical=False) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ['notes', 'users']) self.assertEqual(len(api._canonicals), 2)
def test_register(self): # NOTE: these have all been registered in core.tests.api_urls api = Api() self.assertEqual(len(api._registry), 0) api.register(NoteResource()) self.assertEqual(len(api._registry), 1) self.assertEqual(sorted(api._registry.keys()), ["notes"]) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) api.register(UserResource()) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(api._canonicals), 2) api.register(UserResource(), canonical=False) self.assertEqual(len(api._registry), 2) self.assertEqual(sorted(api._registry.keys()), ["notes", "users"]) self.assertEqual(len(api._canonicals), 2) self.assertRaises(ValueError, api.register, NoteResource)
def test_urls(self): api = Api() api.register(NoteResource()) api.register(UserResource()) patterns = api.urls self.assertEqual(len(patterns), 3) self.assertEqual(sorted([pattern.name for pattern in patterns if hasattr(pattern, 'name')]), ['api_v1_top_level']) self.assertEqual([[pattern.name for pattern in include.url_patterns if hasattr(pattern, 'name')] for include in patterns if hasattr(include, 'reverse_dict')], [['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail'], ['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail']]) api = Api(api_name='v2') api.register(NoteResource()) api.register(UserResource()) patterns = api.urls self.assertEqual(len(patterns), 3) self.assertEqual(sorted([pattern.name for pattern in patterns if hasattr(pattern, 'name')]), ['api_v2_top_level']) self.assertEqual([[pattern.name for pattern in include.url_patterns if hasattr(pattern, 'name')] for include in patterns if hasattr(include, 'reverse_dict')], [['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail'], ['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail']])
def test_urls(self): api = Api() api.register(NoteResource()) api.register(UserResource()) patterns = api.urls self.assertEqual(len(patterns), 3) self.assertEqual( sorted([pattern.name for pattern in patterns if hasattr(pattern, "name")]), ["api_v1_top_level"] ) self.assertEqual( [ [pattern.name for pattern in include.url_patterns if hasattr(pattern, "name")] for include in patterns if hasattr(include, "reverse_dict") ], [ ["api_dispatch_list", "api_get_schema", "api_get_multiple", "api_dispatch_detail"], ["api_dispatch_list", "api_get_schema", "api_get_multiple", "api_dispatch_detail"], ], ) api = Api(api_name="v2") api.register(NoteResource()) api.register(UserResource()) patterns = api.urls self.assertEqual(len(patterns), 3) self.assertEqual( sorted([pattern.name for pattern in patterns if hasattr(pattern, "name")]), ["api_v2_top_level"] ) self.assertEqual( [ [pattern.name for pattern in include.url_patterns if hasattr(pattern, "name")] for include in patterns if hasattr(include, "reverse_dict") ], [ ["api_dispatch_list", "api_get_schema", "api_get_multiple", "api_dispatch_detail"], ["api_dispatch_list", "api_get_schema", "api_get_multiple", "api_dispatch_detail"], ], )
def test_top_level_jsonp(self): api = Api() api.serializer.formats = ['jsonp'] api.register(NoteResource()) api.register(UserResource()) request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} request.GET = {'callback': 'foo'} resp = api.top_level(request) self.assertEqual(resp.status_code, 200) self.assertEqual(resp['content-type'].split(';')[0], 'text/javascript') self.assertEqual(resp.content.decode('utf-8'), 'foo({"notes": {"list_endpoint": "/api/v1/notes/", "schema": "/api/v1/notes/schema/"}, "users": {"list_endpoint": "/api/v1/users/", "schema": "/api/v1/users/schema/"}})') request = HttpRequest() request.META = {'HTTP_ACCEPT': 'text/javascript'} request.GET = {'callback': ''} # Regression: We expect this, which is fine, but this used to # be an import error. with self.assertRaises(BadRequest): api.top_level(request)
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import url, include from api.resources import UserResource, DescriptionResource from tastypie.api import Api v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(DescriptionResource()) urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/', include(v1_api.urls)), ]
from django.conf.urls import patterns, include, url from django.contrib import admin from tastypie.api import Api from telostats.stations.api import StationResource, SeriesResource admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(StationResource()) v1_api.register(SeriesResource()) urlpatterns = patterns( '', url(r'^', include('telostats.stations.urls')), url(r'^api/', include(v1_api.urls)), url(r'^admin/', include(admin.site.urls)), )
from tastypie.api import Api from .api import ( DeviceTokenResource, PhotoResource, UserResource, DentistProfileResource, AppointmentResource, EmergencyScheduleResource, NotificationResource, BookResource, UserCreateResource, UserProfileResource, NoteResource, ) v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(DeviceTokenResource()) v1_api.register(PhotoResource()) v1_api.register(DentistProfileResource()) v1_api.register(AppointmentResource()) v1_api.register(EmergencyScheduleResource()) v1_api.register(NotificationResource()) v1_api.register(BookResource()) v1_api.register(UserCreateResource()) v1_api.register(UserProfileResource()) v1_api.register(NoteResource()) urlpatterns = patterns( '', (r'^', include(v1_api.urls)),
from django.conf.urls import include, patterns, url from tastypie.api import Api from mkt.abuse.resources import AppAbuseResource, UserAbuseResource # Abuse API. abuse = Api(api_name='abuse') abuse.register(UserAbuseResource()) abuse.register(AppAbuseResource()) api_patterns = patterns('', url('^', include(abuse.urls)), )
class ApiViewTestCase(TestCase): def setUp(self): super().setUp() self.api = Api(api_name='v1') def tearDown(self): self.clear_resource() def clear_resource(self): for _url in urlpatterns: if str(_url.pattern) == '^api/': urlpatterns.remove(_url) def register_resource(self, resource): self.api.register(resource) urlpatterns.append(url(r'^api/', include(self.api.urls)), ) def test__is_api(self): """ 测试is_api是否有效 :return: """ class UserResource(BaseModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' @api_view() def a(self, request, *args, **kwargs): return self.create_response(request) user_resource = UserResource() self.register_resource(user_resource) r = self.client.get('/api/v1/user/a/') self.assertEqual('{"_code": 0, "_message": ""}', r.content.decode()) self.assertEqual('user_a', user_resource.prepend_url_list[0].name) self.assertEqual('^(?P<resource_name>user)/a/', str(user_resource.prepend_url_list[0].pattern)) def test_url_path_and_url_name(self): """ 测试定制url_name 和 url_path :return: """ class UserResource(BaseModelResource): class Meta: object_class = User resource_name = 'test_url_path_and_url_name' @api_view(url_name='test_url_name', url_path='test_url_path') def a(self, request, *args, **kwargs): return self.create_response(request) user_resource = UserResource() self.register_resource(user_resource) r = self.client.get( '/api/v1/test_url_path_and_url_name/test_url_path/') self.assertEqual('{"_code": 0, "_message": ""}', r.content.decode()) self.assertEqual('test_url_name', user_resource.prepend_url_list[0].name) self.assertEqual( '^(?P<resource_name>test_url_path_and_url_name)/test_url_path/', str(user_resource.prepend_url_list[0].pattern)) def _test_method(self, method: str): now_resource_name = f'test_method_check_{method}' class UserResource(BaseModelResource): class Meta: object_class = User resource_name = now_resource_name @api_view(allowed_methods=[method]) def a(self, request, *args, **kwargs): return self.create_response(request) user_resource = UserResource() self.register_resource(user_resource) r = self.client.get(f'/api/v1/{now_resource_name}/a/') if method == 'get': self.assertEqual(200, r.status_code) else: self.assertEqual(405, r.status_code) r = self.client.post(f'/api/v1/{now_resource_name}/a/') if method == 'post': self.assertEqual(200, r.status_code) else: self.assertEqual(405, r.status_code) def test_method_check(self): """ 测试allowed_methods是否有效 :return: """ self._test_method('get') self._test_method('post') def test_auth(self): """ 测试auth选项是否有效 :return: """ class TestAuthentication(Authentication): def is_authenticated(self, request, **kwargs): return False class UserResource(BaseModelResource): class Meta: object_class = User resource_name = 'test_auth' authentication = TestAuthentication() @api_view(auth=True) def a(self, request, *args, **kwargs): return self.create_response(request, {}) user_resource = UserResource() self.register_resource(user_resource) r = self.client.get('/api/v1/test_auth/a/') self.assertEqual(401, r.status_code) def test_single_api(self): """ 测试单个对象的api :return: """ test_pk = 'e7f7d55a-4c45-4c45-a0b4-6724435168d7' test_case = self class UserResource(BaseModelResource): class Meta: object_class = User resource_name = 'test_single_api' queryset = User.objects.all() @api_view(single_api=True) def a(self, request, pk, *args, **kwargs): test_case.assertEqual(test_pk, pk) return self.create_response(request) user_resource = UserResource() self.register_resource(user_resource) r = self.client.get( '/api/v1/test_single_api/67ed3642-7b63-4f84-80b0-6cbdafac7253/') self.assertEqual(404, r.status_code) r = self.client.get(f'/api/v1/test_single_api/{test_pk}/a/') self.assertEqual(200, r.status_code)
# along with this program; if not, see <http://www.gnu.org/licenses/>. from django.conf import settings from django.conf.urls import include, patterns from django.contrib import admin from tastypie.api import Api from pootle_language.api import LanguageResource from pootle_project.api import ProjectResource from pootle_translationproject.api import TranslationProjectResource admin.autodiscover() API_VERSION = 'v1' pootle_api = Api(api_name=API_VERSION) pootle_api.register(LanguageResource()) pootle_api.register(ProjectResource()) pootle_api.register(TranslationProjectResource()) urlpatterns = patterns( '', (r'^django_admin/', include(admin.site.urls)), # JavaScript i18n ( r'^jsi18n/$', 'django.views.i18n.javascript_catalog', { 'packages': ('pootle', ), },
2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from users.api import QuestionResource from game.api import GameResource from leaderboard.api import LeaderBoardResource from tastypie.api import Api v1_api = Api(api_name='v1') v1_api.register(QuestionResource()) v2_api = Api(api_name='v2') v2_api.register(QuestionResource()) v2_api.register(GameResource()) v3_api = Api(api_name='v3') v3_api.register(QuestionResource()) v3_api.register(GameResource()) v3_api.register(LeaderBoardResource()) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(v1_api.urls)), path('api/', include(v2_api.urls)),
from django.urls import path from django.conf.urls import url, include from django.conf.urls import url, include from tastypie.api import Api from publication.api.resources import PublicationsResource, CategoryResource from base.api.resources import PartnersResource, AboutResource from project.api.resources import ProjectResource, SearchResource, GeoResource as GResource from project.api.denonciation import DenonciationResource from project.api.comments import CommentsResource from event.api.resources import EventResource from geo.api.resources import PDECSResource, GeoResource v1_api = Api(api_name='v1') v1_api.register(CategoryResource()) v1_api.register(PublicationsResource()) v1_api.register(PartnersResource()) v1_api.register(EventResource()) v1_api.register(ProjectResource()) v1_api.register(AboutResource()) v1_api.register(SearchResource()) v1_api.register(DenonciationResource()) v1_api.register(CommentsResource()) v1_api.register(GeoResource()) v1_api.register(PDECSResource()) v1_api.register(GResource())
from django.conf.urls import patterns, include, url from api import OrganizationResource, UserProfileResource, CourseResource, ProblemResource, EssayResource, EssayGradeResource, UserResource, CreateUserResource, MembershipResource from tastypie.api import Api v1_api = Api(api_name='v1') v1_api.register(OrganizationResource()) v1_api.register(UserProfileResource()) v1_api.register(CourseResource()) v1_api.register(ProblemResource()) v1_api.register(EssayResource()) v1_api.register(EssayGradeResource()) v1_api.register(UserResource()) v1_api.register(CreateUserResource()) v1_api.register(MembershipResource()) urlpatterns = patterns('', (r'^api/', include(v1_api.urls)), ) urlpatterns+=patterns('freeform_data.views', url(r'^login/$','login'), url(r'^logout/$','logout'), )
from api.resources import ParkResource, \ FacilityResource, \ EntryResource, \ NeighborhoodResource, \ ActivityResource, \ ParktypeResource, \ ExploreParkResource, \ ExploreFacilityResource, \ ParkNameResource, \ MBTAResource, \ ExploreActivityResource, \ FacilitytypeResource admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(ActivityResource()) v1_api.register(EntryResource()) v1_api.register(ExploreActivityResource()) v1_api.register(ExploreFacilityResource()) v1_api.register(ExploreParkResource()) v1_api.register(FacilityResource()) v1_api.register(FacilitytypeResource()) v1_api.register(MBTAResource()) v1_api.register(NeighborhoodResource()) v1_api.register(ParkNameResource()) v1_api.register(ParkResource()) v1_api.register(ParktypeResource()) urlpatterns = patterns( '',
from tastypie.api import Api from alphanumeric.api.resources import ProductResource api = Api(api_name='v1') api.register(ProductResource(), canonical=True) urlpatterns = api.urls
from django.conf.urls import url, include from clist import views from tastypie.api import NamespacedApi as Api from clist.api import v1 app_name = 'clist' api_v1 = Api(api_name="v1", urlconf_namespace=f'{app_name}:api') api_v1.register(v1.ResourceResource()) api_v1.register(v1.ContestResource()) urlpatterns = [ url(r'^$', views.main, name='main'), url(r'^resources/$', views.resources, name='resources'), url(r'^resources/dumpdata/$', views.resources_dumpdata, name='resources_dumpdata'), url(r'^resource/(.*)/$', views.resource, name='resource'), url(r'^get/events/$', views.get_events), url(r'^problems/$', views.problems, name='problems'), url(r'^api/', include((api_v1.urls, app_name), namespace='api')), url( r'^api/v1/doc/', include(('tastypie_swagger.urls', app_name), namespace='tastypie_swagger'), kwargs={ 'version': '1.0', 'tastypie_api_module': api_v1, 'namespace': 'clist:tastypie_swagger', },
from django.conf.urls.defaults import * from django.conf import settings from libs.api import UserResource from tastypie.api import Api from django.contrib.staticfiles.urls import staticfiles_urlpatterns api = Api(api_name='api') api.register(UserResource()) # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', (r'^$', include('apps.springboard.urls')), (r'^admin/', include(admin.site.urls)), (r'^courses/', include('apps.courses.urls', namespace="courses", app_name="courses")), (r'^profiles/', include('apps.profiles.urls', namespace="profiles", app_name="profiles")), (r'^alerts/', include('apps.alerts.urls', namespace="alerts", app_name="alerts")), (r'^tinymce/', include('tinymce.urls')), (r'^', include(api.urls)), url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'accounts/login.html'}, name="login"), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login',
from django.conf.urls import patterns, url, include from tastypie.api import Api from .api import UserResource, CreateUserResource # Create an empty pattern so that we can just build it using += urlpatterns = patterns(None) #============================================================================== # API Resources #============================================================================== v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(CreateUserResource()) urlpatterns += patterns( '', url(r'^api/', include(v1_api.urls)), )
from django.conf.urls.defaults import patterns, include, url from tastypie.api import Api from api import * from django.contrib import admin admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(UserResource()) v1_api.register(CurrentAccountResource()) urlpatterns = patterns('', url(r'^$', include('currentaccount.urls')), url(r'^current_account/', include('currentaccount.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(v1_api.urls)), url(r'^accounts/login/', 'django.contrib.auth.views.login', { 'template_name' : 'currentaccount/login.html'} ), )
from api import ConversationResource, SpeakerResource, MessageResource, SentenceResource, WordResource from tastypie.api import Api from django.conf.urls import patterns, include, url v1_api = Api(api_name='v1') v1_api.register(ConversationResource()) v1_api.register(SpeakerResource()) v1_api.register(MessageResource()) v1_api.register(SentenceResource()) v1_api.register(WordResource()) urlpatterns = patterns( '', url('', include(v1_api.urls)), )
Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from tastypie.api import Api from django.conf import settings from app.api import BookResource, TagResource, CategoryResource, ArticleResource import app.urls v1_api = Api(api_name='v1') v1_api.register(BookResource()) v1_api.register(TagResource()) v1_api.register(CategoryResource()) v1_api.register(ArticleResource()) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^traditional/', include(app.urls)), # 传统的 视图url 分发到app.url中 url(r'^api/', include(v1_api.urls)), # tastypie restful url(r'^$', TemplateView.as_view(template_name="index.html")), ] if settings.DEBUG: import debug_toolbar
from tastypie.api import Api from .api import ProcessResource api = Api(api_name='v1') api.register(ProcessResource()) urlpatterns = api.urls
from crits.domains.api import DomainResource from crits.emails.api import EmailResource from crits.events.api import EventResource from crits.indicators.api import IndicatorResource, IndicatorActivityResource from crits.ips.api import IPResource from crits.objects.api import ObjectResource from crits.pcaps.api import PCAPResource from crits.raw_data.api import RawDataResource from crits.relationships.api import RelationshipResource from crits.samples.api import SampleResource from crits.screenshots.api import ScreenshotResource from crits.services.api import ServiceResource from crits.targets.api import TargetResource from crits.standards.api import StandardsResource v1_api = Api(api_name='v1') v1_api.register(ActorResource()) v1_api.register(ActorIdentifierResource()) v1_api.register(CampaignResource()) v1_api.register(CertificateResource()) v1_api.register(CommentResource()) v1_api.register(DomainResource()) v1_api.register(EmailResource()) v1_api.register(EventResource()) v1_api.register(IndicatorResource()) v1_api.register(IndicatorActivityResource()) v1_api.register(IPResource()) v1_api.register(ObjectResource()) v1_api.register(PCAPResource()) v1_api.register(RawDataResource()) v1_api.register(RelationshipResource())
from django.contrib import admin from django.views.generic import RedirectView from django.conf import settings from data_manager.api import LayerResource, ThemeResource, TocThemeResource from tastypie.api import Api from django.contrib.staticfiles.urls import staticfiles_urlpatterns import visualize import explore #from mapproxy.views import proxy_view #import map_proxy # print dir(map_proxy) admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(LayerResource()) v1_api.register(ThemeResource()) v1_api.register(TocThemeResource()) urlpatterns = patterns('', url('', include('social.apps.django_app.urls', namespace='social')), (r'^api/', include(v1_api.urls)), (r'^mp_profile/', include('mp_profile.urls')), #(r'^sdc/', include('scenarios.urls')), #(r'^drawing/', include('drawing.urls')), (r'^data_manager/', include('data_manager.urls')), #(r'^learn/', include('learn.urls')), #(r'^scenario/', include('scenarios.urls')), (r'^explore/', include('explore.urls')),
from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic import TemplateView from tastypie.api import Api from miescuela.api import * v1_api = Api(api_name='v1') v1_api.register(ResultadoGlobalResource()) v1_api.register(EscuelaResource()) v1_api.register(LocalidadResource()) admin.autodiscover() urlpatterns = patterns( '', # url(r'^$', TemplateView.as_view(template_name="index.html"), name='base_index'), url(r'^api/', include(v1_api.urls)), url(r'^admin/', include(admin.site.urls)), )
from .views.home import HomeView from .views.static import StaticView # # Home view. # urlpatterns = patterns( '', url(r'^/?$', HomeView.as_view(), name='home'), ) # # API routes. # api = Api(api_name=u"v1") urlpatterns += patterns('', (r'^api/', include(api.urls))) # # Assets. # urlpatterns += patterns( '', url(r'^%s(?P<path>.*)$' % re.escape(settings.STATIC_URL.lstrip('/')), StaticView.as_view(), { 'cache_forever': True, 'insecure': True })) urlpatterns += app_urlpatterns
from django.contrib import admin from django.contrib.sitemaps.views import sitemap from tastypie.api import Api from froide.publicbody.api import (PublicBodyResource, JurisdictionResource, FoiLawResource) from froide.foirequest.api import (FoiRequestResource, FoiMessageResource, FoiAttachmentResource) from froide.publicbody.views import (PublicBodySitemap, FoiLawSitemap, JurisdictionSitemap, show_publicbody) from froide.foirequest.views import (index, search, dashboard, auth, FoiRequestSitemap, shortlink) v1_api = Api(api_name='v1') v1_api.register(PublicBodyResource()) v1_api.register(JurisdictionResource()) v1_api.register(FoiLawResource()) v1_api.register(FoiRequestResource()) v1_api.register(FoiMessageResource()) v1_api.register(FoiAttachmentResource()) class StaticViewSitemap(Sitemap): priority = 1.0 changefreq = 'daily' def items(self): return ['index', 'foirequest-list']
from django.views.generic import RedirectView from django.views.generic import TemplateView from decorator_include import decorator_include from tastypie.api import Api from rhizome.api.resources import * from rhizome.api.decorators import api_debug from rhizome import views admin.autodiscover() ###################### # TASTYPIE Endpoints # ###################### v1_api = Api(api_name='v1') v1_api.register(agg_refresh.AggRefreshResource()) v1_api.register(cache_meta.CacheMetaResource()) v1_api.register( calculated_indicator_component.CalculatedIndicatorComponentResource()) v1_api.register(custom_chart.CustomChartResource()) v1_api.register(custom_dashboard.CustomDashboardResource()) v1_api.register(date_datapoint.DateDatapointResource()) v1_api.register(doc_datapoint.DocDataPointResource()) v1_api.register(doc_detail_type.DocDetailTypeResource()) v1_api.register(doc_trans_form.DocTransFormResource()) v1_api.register(document.DocumentResource()) v1_api.register(document_detail.DocumentDetailResource()) v1_api.register(geo.GeoResource()) v1_api.register(group.GroupResource())
from django.conf.urls import patterns, include, url # TASTYPIE API from tastypie.api import Api from gtfs.api import AlertResource v1_api = Api(api_name='v1') v1_api.register(AlertResource()) # GENERIC VIEWS from gtfs.views import IndexView, DetailView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', # Examples: # url(r'^$', 'malerts.views.home', name='home'), # url(r'^malerts/', include('malerts.foo.urls')), # url(r'^$', 'gtfs.views.alerts_html'), url(r'^alert.asciipb$', 'gtfs.views.alerts_ascii'), url(r'^api/', include(v1_api.urls)), url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', DetailView.as_view(), name="detail"), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # admin addons
from app_ambiente.apps.soap_server.api import * from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from .api import LoginResource from tastypie.api import Api ambiente_api = Api(api_name='ambiente') ambiente_api.register(LoginResource()) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(ambiente_api.urls)), url(r'^', include('app_ambiente.apps.principal.urls')), url(r'^users/', include('app_ambiente.apps.users.urls')), url(r'^solicitudes/', include('app_ambiente.apps.solicitudes.urls')), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ]
from apps.main.api import MemberByFBTokenResource from apps.main.api import MemberResource from apps.main.api import NotificationResource from apps.main.api import MessageResource from apps.main.api import AddBidResource from apps.main.api import ClaimBidResource from apps.main.api import RemBidResource from apps.main.api import RegisterInvitationResource from apps.main.api import ServerClockResource from apps.main.api import PaypalPaymentInfoResource from apps.main.api import IOPaymentInfoResource from apps.main.api import AppleIbidPackageIdsResource v1_api = Api(api_name='v1') v1_api.register(RegisterInvitationResource()) v1_api.register(ServerClockResource()) v1_api.register(NotificationResource()) v1_api.register(MemberResource()) v1_api.register(ConverTokensResource()) v1_api.register(MemberByFBTokenResource()) v1_api.register(CategoryResource()) v1_api.register(ItemResource()) v1_api.register(AuctionResource()) v1_api.register(MemberAuctionsResource()) v1_api.register(BidPackageResource()) v1_api.register(AddBidResource()) v1_api.register(RemBidResource()) v1_api.register(ClaimBidResource())
from django.conf.urls.defaults import patterns, url, include from tastypie.api import Api from api import * from .views import * v1 = Api(api_name='v1') v1.register(ProfileResource()) # v1.register(EntryResource()) urlpatterns = patterns( '', url(r'^duo/signup/', Signup.as_view(), name='signup'), # url(r'^(?P<pk>\d+)/$', # DetailView.as_view(), # name="detail"), # url(r'^api/', include(v1.urls)), url(r'^duo/api/', include(v1.urls)), )
def setUp(self): super().setUp() self.api = Api(api_name='v1')
from django.conf.urls.defaults import * from tastypie.api import Api from api import TestResource api = Api('test') api.register(TestResource()) urlpatterns = patterns('', (r'^api/', include(api.urls)), )
from rest_framework.routers import SimpleRouter from tastypie.api import Api from tastypie_services.services import (ErrorResource, SettingsResource) from mkt.submit.api import PreviewResource, StatusResource, ValidationResource from mkt.api.base import AppRouter, handle_500, SlugRouter from mkt.api.resources import (AppResource, CarrierResource, CategoryViewSet, ConfigResource, error_reporter, RefreshManifestViewSet, RegionResource) from mkt.collections.views import CollectionViewSet from mkt.features.views import AppFeaturesList from mkt.ratings.resources import RatingResource from mkt.search.api import SearchResource, SuggestionsResource api = Api(api_name='apps') api.register(ValidationResource()) api.register(AppResource()) api.register(PreviewResource()) api.register(SearchResource()) api.register(SuggestionsResource()) api.register(StatusResource()) api.register(RatingResource()) rocketfuel = SimpleRouter() rocketfuel.register(r'collections', CollectionViewSet, base_name='collections') apps = SlugRouter() apps.register(r'category', CategoryViewSet, base_name='app-category')