【问题标题】:How to tell which backend files are associated with frontend files?如何判断哪些后端文件与前端文件相关联?
【发布时间】:2016-04-29 16:56:24
【问题描述】:

我最近开始在一家拥有庞大代码库的科技公司实习,目前正试图从前端(用 JS 编写)提取一个值并将其传递到应用程序的后端(用 Django 编写)。我可以成功访问前端中的值,但是现在我不确定这个JS在后端关联的是什么文件,所以我不知道如何将它传递给后端。有没有建议的方法来解决这个问题?很抱歉提出这样一个业余问题,但这对我来说是全新的,我很困惑!

【问题讨论】:

  • 您可以添加其他信息吗?前端结构如何?什么时候需要将值从前端传递到后端?那是一种什么样的价值?
  • @patrick 我不熟悉典型的前端结构,但我知道这个前端是使用 Backbone/Marionette 和车把模板构建的。我需要将值(它是一个字符串)从前端的模式(在 .js 文件中访问)传递给一个后端 python 函数,该函数将检查该值是否有效。

标签: javascript django frontend backend codebase


【解决方案1】:

在 django 中,用于将数据发送到(通过 POST/GET)或导航到(通过浏览器)的 URL 端点(路由)在名为 urls.py 的文件中指定。有一个主要的urls.py 文件位于包含settings.py 和wsgi.py 的文件夹中,它包含将请求的URL 映射到其他urls.py 文件的代码。其他urls.py 文件将请求的URL 映射到views.py 中定义的函数,这些函数呈现页面或处理数据提交(在其他框架中它们可能被称为“控制器”)。

根据您当前的 URL,查看从主 urls.py 开始的每个 urls.py 文件,直到找到该 URL 映射到的 views.py 文件。

例如,如果我当前的网址是/profile

# MyApp/urls.py (note the include('profile.urls') argument)
urlpatterns = patterns('',  
    url(r'^profile/', include('profile.urls'), name='profile'),
    ...
)



# profile/urls.py
from profile import views
urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),      # /profile (this url is matched)
    url(r'^ajax/$', views.ajax, name='ajax'),   # /profile/ajax
    url(r'^user/$', views.user, name='user')    # /profile/user
)



# profile/views.py
def index(request):
    context = RequestContext(request)
    context_dict = {
        'user':request.user,
        'numCheckIns':Event.objects.filter(CheckedInParticipants__id=request.user.id).count,
        'numCommits':Event.objects.filter(participants__id=request.user.id).count,
        'gameLog': Event.objects.filter(checkedInParticipants__id=request.user.id)
    }
    return render_to_response('profile/index.html', context_dict, context)



def ajax(request):
    if request.method == 'POST':
        ...
def user(request):
    ...

与/profile 处的渲染视图相关的文件可以追溯到profile/views.py,执行的函数称为index,包含在其中。

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 2015-08-15
    • 2020-11-28
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多