1

我试图弄清楚为我的 api 创建非 orm 端点是否有意义。我已经看过文档的“将 Tastypie 与非 ORM 数据源一起使用”部分,但我更多地考虑处理表单等。例如:将数据传递到将处理和发送电子邮件的端点。我不会将任何东西保存到数据库中,我只想验证表单并发送它。我是在文档中遗漏了什么,还是我只是在叫错树?

4

1 回答 1

0

我认为您可以只在您的函数中定义一个函数views.py并处理请求,而无需真正使用tastepie:

这是一个将新用户注册到 Django webapp 的示例;您可能可以通过处理请求中的表单数据来重新利用它来发送电子邮件。

# In views.py:
...
from django.http import HttpResponse
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate
from django.http import Http404
from django.utils import timezone
from models import *
from api import *
from django.utils import simplejson
...

# REST endpoint for user registration
# Enforces server-side mediation (input validation)
# On failure, raises Http404
# On success, redirects to registration success page
def register_user(request):
    if request.method != 'POST':
        raise Http404('Only POSTs are allowed')

    # acquire params
    username = request.POST['username']
    password = request.POST['password']
    repeatpw = request.POST['repeatpw']
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']

    # Server-side mediation to check for invalid input
    if username == '' or username is None:
        raise Http404('Server-side mediation: Invalid Username')

    if len(username) > 30:
        raise Http404('Server-side mediation: username must be 30 characters or fewer')

    if len(first_name) > 30:
        raise Http404('Server-side mediation: first name must be 30 characters or fewer')

    if len(last_name) > 30:
        raise Http404('Server-side mediation: last name msut be 30 characters or fewer')

    if len(password) < 4:
        raise Http404('Server-side mediation: Password too short')

    if password != repeatpw:
        raise Http404('Server-side mediation: Password Mismatch')

    # This try-except block checks existence of username conflict
    try:
        test_user_exists = User.objects.get(username__exact=username)
        if test_user_exists != None:
            raise Http404('Server-side mediation: Username exists')
    except User.DoesNotExist:
        pass

    # Input passes all tests, proceed with user creation
    user = User.objects.create_user(username, 'default@nomail.com', password)
    group = Group.objects.get(name='Standard')
    user.first_name = first_name
    user.last_name = last_name
    user.groups.add(group)
    user.is_staff = False    
    user.save()

    # Build confirmation JSON
    confirmation = {
            'action': 'register_user',
            'username': username,
            'success': 'yes',
    }

    json_return = simplejson.dumps(confirmation)

    # return JSON of the success confirmation
    return HttpResponse(json_return, mimetype='application/json')
于 2012-12-06T16:07:56.937 回答