Django在视图中保存调用api的数据

时间:2018-01-24 03:07:08

标签: python django django-rest-framework

所以我有一个视图,它有一个调用另一个django项目API的Get和Post请求。但我想保存从api调用中获得的信息。

项目1有一个约会表,其中包含以下字段clinic IdtimequeueNo。当我对Project 2进行Post请求以创建/创建约会时,成功创建时,它将显示我想要保存到Project 1约会表数据库中的那3个字段。我该怎么做 ?我的约会也有一个API,所以如何将它保存在那里?

以下是我将视图调用api到另一个django项目的代码

views.py

@csrf_exempt
def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST)
    else:
        r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET)
    if r.status_code == 200:
        # r.text, r.content, r.url, r.json
        return HttpResponse(r.text)
    return HttpResponse('Could not save data')

2 个答案:

答案 0 :(得分:4)

假设Project 2中的端点返回一个JSON响应,其中包含您需要的字段:

{
    "clinicId": 1,
    "time": some-time-string,
    "queueNo": 2
}

您可以在致电r.json()后发出请求后检索回复。

在此基础上,您可以将r.json()视为字典,并使用Appointment.objects.create(**r.json())创建实例。这是它的外观。

@csrf_exempt
def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST)
    else:
        r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET)

    if r.status_code == 200 and request.method == 'POST':
        # Convert response into dictionary and create Appointment
        data = r.json()
        # Construct required dictionary
        appointment_attrs = {
            "clinicId": data["some-key-that-points-to-clinicid"],
            "time": data["some-key-that-points-to-time"],
            "queueNo": data["some-key-that-points-to-queue-num"]
        }
        appointment = Appointment.objects.create(**appointment_attrs)
        # r.text, r.content, r.url, r.json
        return HttpResponse(r.text)
    elif r.status_code == 200:  # GET response
        return HttpResponse(r.text)

    return HttpResponse('Could not save data')

答案 1 :(得分:0)

首先必须从响应中提取数据。 如果您正在使用JSON库以及您正在通过data = r.json()进行回复的API,则可以执行data之类的操作。

我不知道你的第二个API的回复结构,但我想你可以从Appointement对象中获取你的字段。

然后,您可以使用您正在使用的任何数据库界面保存您想要的内容。如果它是django ORM,并且你在某个地方有Appointment( clinic_id=data["clinic_id"], time=data["time"], queueNo=data["queueNo"] ).save() 模型,你可以做类似的事情

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 1000 ;


    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    List<Item> items;
    CustomAdapter adapter;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull     String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case PERMISSION_REQUEST_CODE:
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(this,"Permission Denied", Toast.LENGTH_SHORT).show();
            }
            break;

        }
    }




    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str="Click on Wallpaper to set  Wallpaper";
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
        mDrawerLayout=(DrawerLayout) findViewById(R.id.dl);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationView navigationView = (NavigationView) findViewById(R.id.Navigation_v);
        setupDrawerContent(navigationView);
        ActionBar actionBar = getSupportActionBar();

        recyclerView =(RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        initItem();

        //start service and play music
        startService(new Intent(MainActivity.this, SoundService.class));
    }
    private void  initItem() {

        items = new ArrayList<>();

        items.add(new Item(0,"https://images8.alphacoders.com/532/thumb-1920-532407.jpg"));
        items.add(new Item(1, "https://images5.alphacoders.com/394/thumb-1920-394511.jpg"));
        items.add(new Item(1,"https://images5.alphacoders.com/408/thumb-1920-408539.jpg"));

        adapter = new CustomAdapter(this,items);
        recyclerView.setAdapter(adapter);    
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onDestroy() {
        //stop service and stop music
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onDestroy();
    }
    public void selectItemDrawer(MenuItem menuItem){
        Fragment myFragment = null;
        Class fragmentClass;
        switch (menuItem.getItemId()) {

            case  R.id.walkthrough:
                fragmentClass = Walkthrough.class;
                break;
            case R.id.Fav:
                fragmentClass = Favourites.class;
                break;
            case R.id.info:
                fragmentClass = About.class;
                break;
            default:
                fragmentClass = Walkthrough.class;


        }
        try {
            myFragment = (Fragment) fragmentClass.newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
        setTitle(menuItem.getTitle());
        mDrawerLayout.closeDrawers();
    }
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectItemDrawer(item);
                return true;
            }
        });
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(this, MainActivity.class));
    }
}

你已经完成了......