Microsoft graph api 如何使用图形api在Django中使用POST请求?

Microsoft graph api 如何使用图形api在Django中使用POST请求?,microsoft-graph-api,azure-ad-graph-api,instagram-graph-api,microsoft-graph-mail,Microsoft Graph Api,Azure Ad Graph Api,Instagram Graph Api,Microsoft Graph Mail,基本上,我正在尝试创建一个表单,该表单将在我的Azure Active Directory中创建一个新用户。 根据,我需要使用给定的HTTP请求。 有谁能指导我如何做到这一点吗。 如果提供了代码,那么它将非常棒,否则解释或指导也非常棒 我已经能够成功地运行带有GET请求的教程代码。现在我想用一个graph_client.POST(,data={'userPrincipalName':'sue@example.com结构类型。不幸的是,这会生成一条HTTP 400消息,其格式为“code”:“Ba

基本上,我正在尝试创建一个表单,该表单将在我的Azure Active Directory中创建一个新用户。 根据,我需要使用给定的HTTP请求。 有谁能指导我如何做到这一点吗。 如果提供了代码,那么它将非常棒,否则解释或指导也非常棒

我已经能够成功地运行带有GET请求的教程代码。现在我想用一个graph_client.POST(,data={'userPrincipalName':'sue@example.com结构类型。不幸的是,这会生成一条HTTP 400消息,其格式为“code”:“BadRequest”,“message”:“实体只允许使用JSON内容类型头进行写入。”。教程构造是否适用于POST请求

如果您可以指导我在哪里添加行以使POST方法成功工作。我附上我的代码截图,请查看以下内容:-

HTML页面:-

views.py:-

图形_helper.py-

我们将感谢您的时间和努力。
谢谢…

要调用Microsoft Graph API,必须在请求头中提供访问令牌。下面是请求的一个示例

POST https://graph.microsoft.com/v1.0/users
Content-type: application/json

{
  "accountEnabled": true,
  "displayName": "displayName-value",
  "mailNickname": "mailNickname-value",
  "userPrincipalName": "upn-value@tenant-value.onmicrosoft.com",
  "passwordProfile" : {
    "forceChangePasswordNextSignIn": true,
    "password": "password-value"
  }
}

获取身份验证令牌有两种方法


该错误表示您的帖子中缺少
内容类型的标题。您正在使用,他们的文档显示了如何制作帖子

查看您的代码,我看到的第一个问题是您没有发送任何内容:

new_user = graph_client.post('{0}/users'.format(graph_url))
我记得,您需要显式地设置
内容类型
标题,否则请求库会将您在
数据
参数中传递的任何内容作为表单编码发送,这将不起作用。所以你会有这样的想法:

headers = { 'Authorization' : 'Bearer {0}'.format(token),
            'Accept' : 'application/json',
            'Content-Type' : 'application/json' }
然后,您需要实际构建一些要发送的有效负载。我以前对这个库所做的只是传递一个JSON字符串。所以你会有这样的东西:

new_user = graph_client.post('{0}/users'.format(graph_url)), headers = headers, json = user_json_string)
建议以后发布:不要发布代码的图像。把密码贴出来就行了。它使人们更容易提供帮助:)

views.py

from tutorial.graph_helper import *
from django.urls import reverse
from tutorial.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import dateutil.parser

def home(request):
  context = initialize_context(request)

  return render(request, 'tutorial/home.html', context)

def userslist(request):
  context = initialize_context(request)
  token = get_token(request)
  usersdata = get_users(token)
  if usersdata :
    #for user in usersdata['value']
    print ('users fetched')
    print (usersdata)
  else:
    print('no output')

  print('yeta ka')
  context['usersdata'] = usersdata['value']
  return render(request, 'tutorial/userslist.html',context)

def groupslist(request):
  context = initialize_context(request)
  token = get_token(request)
  groupsdata = get_groups(token)
  if groupsdata :
    #for group in groupsdata['value']
    print ('groups fetched')
    print (groupsdata)
  else:
    print('no output')

  print('yeta ka')
  context['groupsdata'] = groupsdata['value']
  return render(request, 'tutorial/groupslist.html',context)

def newuserindex(request):
  return render(request, 'createsingleuser.html')

def createsingleuser(request):
  context = initialize_context(request)
  token = get_token(request)
  if request.method =='POST':
    context = request.POST  
    context1 = {
      "accountEnabled": 'true',
      "city": context['city'],
      "country": context['country'],
      "department": context['department'],
      "displayName": context['displayName'],
      "givenName": context['givenName'],
      "jobTitle": context['jobTitle'],
      "mailNickname": context['mailNickname'],
      "passwordPolicies": "DisablePasswordExpiration",
      "passwordProfile": {
        "password": "Test1234",
        "forceChangePasswordNextSignIn": 'false'
      },
      "officeLocation": context['officeLocation'],
      "postalCode": context['postalCode'],
      "preferredLanguage": context['preferredLanguage'],
      "state": context['state'],
      "streetAddress": context['streetAddress'],
      "surname": context['surname'],
      "mobilePhone": context['mobilePhone'],
      "usageLocation": context['mobilePhone'],
      "userPrincipalName": context['userPrincipalName']
    }
    newuser = create_user(token,context1)
    print (newuser)

  return render(request, 'tutorial/createsingleuser.html', context)

def initialize_context(request):
  context = {}

  # Check for any errors in the session
  error = request.session.pop('flash_error', None)

  if error != None:
    context['errors'] = []
    context['errors'].append(error)

  # Check for user in the session
  context['user'] = request.session.get('user', {'is_authenticated': False})
  return context

def sign_in(request):
  # Get the sign-in URL
  sign_in_url, state = get_sign_in_url()
  # Save the expected state so we can validate in the callback
  request.session['auth_state'] = state
  # Redirect to the Azure sign-in page
  return HttpResponseRedirect(sign_in_url)

def callback(request):
  # Get the state saved in session
  expected_state = request.session.pop('auth_state', '')
  # Make the token request
  token = get_token_from_code(request.get_full_path(), expected_state)

  # Get the user's profile
  user = get_user(token)

  # Save token and user
  store_token(request, token)
  store_user(request, user)

  return HttpResponseRedirect(reverse('home'))

def sign_out(request):
  # Clear out the user and token
  remove_user_and_token(request)

  return HttpResponseRedirect(reverse('home'))

def calendar(request):
  context = initialize_context(request)

  token = get_token(request)

  events = get_calendar_events(token)

  if events:
    # Convert the ISO 8601 date times to a datetime object
    # This allows the Django template to format the value nicely
    for event in events['value']:
      event['start']['dateTime'] = dateutil.parser.parse(event['start']['dateTime'])
      event['end']['dateTime'] = dateutil.parser.parse(event['end']['dateTime'])

    context['events'] = events['value']

  return render(request, 'tutorial/calendar.html', context)
graph_helper.py

from requests_oauthlib import OAuth2Session
import json
import requests


graph_url = 'https://graph.microsoft.com/v1.0'


def get_user(token):
  graph_client = OAuth2Session(token=token)
  # Send GET to /me
  user = graph_client.get('{0}/me'.format(graph_url))
  # Return the JSON result
  return user.json()

def get_calendar_events(token):
  graph_client = OAuth2Session(token=token)

  # Configure query parameters to
  # modify the results
  query_params = {
    '$select': 'subject,organizer,start,end',
    '$orderby': 'createdDateTime DESC'
  }

  # Send GET to /me/events
  events = graph_client.get('{0}/me/events'.format(graph_url), params=query_params)
  # Return the JSON result
  return events.json()

def get_users(token):
  graph_client = OAuth2Session(token=token)
  # Send GET to /users
  users = graph_client.get('{0}/users'.format(graph_url))
  # Return the JSON result
  return users.json()

def get_groups(token):
  graph_client = OAuth2Session(token=token)
  # Send GET to /groups
  groups = graph_client.get('{0}/groups'.format(graph_url))
  # Return the JSON result
  return groups.json()

def create_user(token, context1):
  graph_client = OAuth2Session(token=token)
  headers = { 'Authorization' : 'Bearer {0}'.format(token),
            'Accept' : 'application/json',
            'Content-Type' : 'application/json' }
  # newuser = graph_client.post('https://graph.microsoft.com/v1.0/users', headers = {"Content-Type":"application/json", data=context1, })
  newuser = graph_client.post('{0}/users'.format(graph_url), headers = headers, json = context1)
  return newuser

谢谢你的帮助。很抱歉,我之前没有提到我有access auth token,我可以使用“GET”请求从azure广告中获取数据,现在我想添加一些更改,因此我需要一个Django POST codeHi示例。你有什么关于它的信息吗?谢谢,Jason。我按照你的指导做了尝试,但还是没有解决。我在下面发布我的代码,请参考我的view.py和graph_helper.py文件。我想我在调用方法或发送数据时做错了。请仔细查看并指导我,好吗,您传递的是字典,而不是JSON字符串,所以请尝试将“JSON=context1”更改为“data=context1”。或者您可以尝试“json=context1.to_json()”(或者类似的东西,从这里的内存来看),我使用了“json=context1”、“data=context1”、“data=json.dumps(context1)”。什么都没用。根据您的建议,我尝试了“json=context1.to_json()”,但我得到的错误是{'dict'对象没有属性'to_json'。这个旧示例可能会帮助您:。从那时起,他们可能已经更改了Requests API,但我就是这样让它工作的。当我有更多的时间来研究这个问题时,我可以提供一个更具体的答案。这是一个伟大的项目。我可能会得到它。但是因为它是用旧版本写的。所以现在它给出了错误,我试图解决错误,但我无法解决最后6个错误。无论如何,对于同一活动“GET”和“POST”方法,您是否有任何Csharp代码引用。我想通过Csharp试试。