티스토리 뷰


필수 코드

console: pip install requests

import requests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests
import json

@csrf_exempt
def push_to_client(lms_id, list_diff_subjects, list_diff_reports):
 
    url = 'https://fcm.googleapis.com/fcm/send'    
 
    headers = {
        'Authorization''key=longlongKey',
        'Content-Type''application/json; UTF-8',
    }
 
    # 한명 지정이면 to, 여럿일 경우 registration_ids[]
    
    content ={'to': token, 'notification': { 'title''title''body''body'}}
    push_req = requests.post(url, data=json.dumps(content), headers=headers)
 
cs



내가 사용하는 코드(title은 과목명, body는 과제명)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import requests
import json

@csrf_exempt
def push_to_client(lms_id, list_diff_subjects, list_diff_reports):
 
    userdata = UserData.objects.get(lms_id = lms_id)
    token = userdata.device_token
    # print('TOKEN ', token)
    # fcm 푸시 메세지 요청 주소
    url = 'https://fcm.googleapis.com/fcm/send'    
    # 인증 정보(서버 키)를 헤더에 담아 전달
    headers = {
        'Authorization''key=longlongkey',
        'Content-Type''application/json; UTF-8',
    }
 
    # 한명 지정이면 to, 여럿일 경우 registration_ids[]
 
    # json 파싱 후 requests 모듈로 FCM 서버에 요청
    if len(list_diff_subjects) > 0:
        for i in range(int(len(list_diff_subjects) / 2)):
            content ={'to': token, 'notification': { 'title': list_diff_subjects[i], 'body': list_diff_subjects[i+1]}}
            push_req = requests.post(url, data=json.dumps(content), headers=headers)
 
    if len(list_diff_reports) > 0:
        for i in range(int(len(list_diff_reports) / 2)):
            content ={'to': token, 'notification': { 'title': list_diff_reports[i], 'body': list_diff_reports[i+1]}}
            push_req = requests.post(url, data=json.dumps(content), headers=headers)
 
    return HttpResponse("<h1>SENDED</h1>")
cs




한명에게 보내면 to

여러명이면 array type registration_ids[]

topic으로 보낼수도 있음


Authorization key는 파이어베이스 콘솔 -> 왼쪽 Project Overview 설정 -> CloudMessaging탭에 서버키 있음




댓글
댓글쓰기 폼