我正在用django/tastpie构建一个RESTful api.在我的开发(本地)环境中运行时,一切都很好,并且可以正确验证.
Marks-MacBook-Pro:~ mshust$ curl http://127.0.0.1:8000/api/v1/speedscreen/ -H 'Authorization: Basic bXNodXN0MToyMjY3' -v
* About to connect() to 127.0.0.1 port 8000 (#0)
* Trying 127.0.0.1...
* connected
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET /api/v1/speedscreen/ HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: 127.0.0.1:8000
> Accept: */*
> Authorization: Basic bXNodXN0MToyMjY3
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 09 Aug 2012 01:36:05 GMT
< Server: WSGIServer/0.1 Python/2.7.2
< Content-Type: …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种在我的一些ModelResource中添加"通用"搜索的方法.使用'v1'api,我希望能够查询已经使用这种url注册的一些ModelResource:/ api/v1 /?q ='blabla'.然后我想恢复一些可以填充查询的ModelResourceS.
你认为最好的方法是什么?
我尝试构建一个GenericResource(Resource),我自己的类重新呈现行数据,但没有成功.你有一些帮助我的链接吗?
问候,
所以我在没有找到答案的情况下阅读了以下帖子:
我的模型使用JSONField来存储任意数据.
class Task(models.Model):
"""
Execution of a Test
"""
results = JSONField(max_length=1000, blank=True)
Run Code Online (Sandbox Code Playgroud)
在python shell中,我可以打印此字段,它呈现以下内容:
[{"name": "tata", "result": "toto"}]
Run Code Online (Sandbox Code Playgroud)
我修改脱水方法删除unicode,但我有以下结果:
**Dehydrate Method:**
def dehydrate_results(self, bundle):
results = json.dumps(bundle.obj.results)
return results
**Tastypie Result**
"results": "[{\"name\": \"Cash In\", \"result\": \"toto\"}]"
Run Code Online (Sandbox Code Playgroud)
我不能在我的javascript应用程序中使用此对象...也许你可以解释我如何从tastypie获得"正常"json输出:
**Wanted Tastypie Result**
"results": [{"name": "Cash In", "result": "toto"}]
Run Code Online (Sandbox Code Playgroud)
谢谢.
我是Django-Tastypie的新手,我看下面的入门示例:http://django-tastypie.readthedocs.org/en/latest/tutorial.html#hooking-up-the-resource-s
是否可以允许包含特定格式的过滤条件的休息URL,用于过滤要返回的对象?
这意味着我必须做一些类似于这个线程的东西:REST urls with tastypie?
我使用python httplib来实现REST api以连接Django tastypie.但每当我尝试获取状态代码时,它都会显示以下错误
AttributeError at /actions/login
HTTPResponse instance has no attribute 'status_code'
Run Code Online (Sandbox Code Playgroud)
我的代码如下
import hashlib
import hmac
from django.shortcuts import render_to_response
from django.template import RequestContext
def loginAction(request):
username=request.POST['email']
password=request.POST['password']
import httplib, urllib
params = urllib.urlencode({'username': username})
#hash username here to authenticate
digest=hmac.new("qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50", str(request.POST['password']),hashlib.sha1).hexdigest()
auth=username+":"+digest
headers = {"Content-type": "application/json","Accept": "text/plain","Authorization":auth}
conn = httplib.HTTPConnection("localhost",8000)
conn.request("POST", "/api/ecp/profile/", params, headers)
conn.set_debuglevel(1)
response = conn.getresponse()
return response
Run Code Online (Sandbox Code Playgroud) 如何dispatch_list在Tastypie中添加自定义字段(在本例中为元代码)?
由于我的模型的自定义保存方法将request.user作为参数,我无法执行POST/PUT请求.
TypeError at /api/obsadmin/observation/23
save() takes at least 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
我正在使用SessionAuthentication()并包含CSRF令牌.
这是相关的模型部分:
def save(self, user, owner=None, *args, **kwargs):
self.updated_by = user.id
super(ObsModel, self).save(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
和资源:
class ObservationResource2(ModelResource):
comments = fields.ToManyField(CommentResource2, 'comments', full=True, null=True)
class Meta:
queryset = Observation.objects.filter(is_verified=True)
authentication = SessionAuthentication()
authorization = DjangoAuthorization()
resource_name = 'observation'
always_return_data = True
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用django tastypie创建一个api.在我的项目中,我有两个模型问题和答案.Answers模型具有问题模型的外键.在我的api.py中,我有两个资源QuestionResource和AnswerResource.
我想要做的是,当我使用api调用检索问题实例时,我也想检索相关的答案实例.我尝试使用在bundle.data dict中添加一个键并在alter_detail_data_to_serialize中实现它.我得到的是响应是一个对象列表而不是序列化的json对象.我得到的是
我的守则是
class QuestionResource(ModelResource):
answer=fields.ToManyField('quiz.api.AnswerResource', 'answer', null=True, full=True)
topic=fields.ForeignKey(TopicResource,'topic')
difficulty=fields.ForeignKey(DifficultyLevelResource, 'difficulty')
class Meta:
queryset = Question.objects.all()
resource_name = 'question'
authorization = Authorization()
serializer = PrettyJSONSerializer()
detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
always_return_data = True
filtering={'id':ALL,
'answer':ALL_WITH_RELATIONS
}
def alter_detail_data_to_serialize(self, request, data):
data.data['answers']=[obj for obj in data.obj.answer_set.all()]
return data
def dehydrate(self,bundle):
bundle.data['related']=bundle.obj.answer_set.all()
return bundle
class AnswerResource(ModelResource):
question=fields.ToOneField('quiz.api.QuestionResource', 'answer', null=True,full=True)
class Meta:
queryset = Answer.objects.all()
resource_name = 'answer'
authorization = Authorization()
serializer = PrettyJSONSerializer()
detail_allowed_methods = ['get', 'post', …Run Code Online (Sandbox Code Playgroud) 我得到以下堆栈无法弄清楚问题是什么.我知道它与我的URLS.pi有关我正在尝试做一个美味的馅饼网址来设置Restfull服务
ImportError: importlib._bootstrap is not a frozen module
Traceback (most recent call last):
File "/usr/local/lib/python3.3/dist-packages/django/core/urlresolvers.py", line 339, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.3/dist-packages/django/core/handlers/base.py", line 101, in get_response
resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python3.3/dist-packages/django/core/urlresolvers.py", line 318, in resolve
for pattern in self.url_patterns:
File "/usr/local/lib/python3.3/dist-packages/django/core/urlresolvers.py", line 346, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.3/dist-packages/django/core/urlresolvers.py", line 341, in urlconf_module
self._urlconf_module = …Run Code Online (Sandbox Code Playgroud) 我使用的Django与Tastypie库和Django的OAuth的工具包,以及用于Django的OAuth的工具包Tastypie认证.
免责声明:我有可能完全错误.如果是这样,请纠正我,引导我走向不那么无知的人.
主要问题:如何安全地创建用户?
我的理解:
get或者post,客户端需要一个令牌.我正在努力解决这个问题.当客户端尝试创建不需要OAuth2的帐户时,我会创建吗?或者有没有办法在没有登录的情况下使用OAuth2,只允许客户创建帐户?
任何帮助深表感谢!