2016-04-03 212 views
5

我正在嘗試從python(2.7)交流firebase上的數據。python中的Firebase用戶身份驗證

這裏是我的規則(上firebseio.com):

{ 
    "rules": { 
     "user": { 
      "$uid": { 
      ".read": "auth != null && auth.uid == $uid", 
      ".write": "auth != null && auth.uid == $uid" 
      } 
     } 
    } 
} 

這裏是我的DATABSE的截圖:

enter image description here

而在去年,我的Python代碼:

from firebase import firebase 
from firebase.firebase import FirebaseApplication, FirebaseAuthentication 

DSN = 'https://<my name>.localhost' 
EMAIL = '[email protected]' 
authentication = FirebaseAuthentication(EMAIL, True, True, extra={'id': '<the user id>'}) 
firebase = FirebaseApplication(DSN, authentication) 
firebase.authentication = authentication 
print authentication.extra 

user = authentication.get_user() 
print user.firebase_auth_token 

現在我無法找到如何獲取數據並向Firebase發送數據和從Firebase發送數據。 我tryed期運用行:result = firebase.get('/users', None, {'print': 'pretty'}),但它給我這個錯誤:

ConnectionError: HTTPSConnectionPool(host='<my name>.localhost', port=443): Max retries exceeded with url: /users/.json?print=pretty&auth=<the token code of the user> (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x02A913B0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) 

誰能給我提供一個工作代碼?

由於提前,

茲維·卡普

+0

如果我不使用DSN會怎麼樣? – marciokoko

回答

6

下面是我們把獲得認證工作的步​​驟。

(1)首先你需要一個Firebase祕密。 在Firebase中創建項目後,點擊設置。然後單擊數據庫並選擇創建一個祕密。 settings

複製你的祕密。它將在稍後進入您的代碼。

secret

(2)你需要你的火力點URL。 它會有這樣的格式:https://.firebaseio.com 也複製這個。

(3)獲取適用於Python的Firebase REST API。 我們用這一個:https://github.com/benletchford/python-firebase-gae 導航到你上面的lib目錄並運行此命令將在火力的代碼放到你的lib目錄:

git clone http://github.com/benletchford/python-firebase-gae lib/firebase 

(4)在你的「main.py」文件(或任何您正在使用)添加以下代碼:

from google.appengine.ext import vendor 
vendor.add('lib') 

from firebase.wrapper import Firebase 

FIREBASE_SECRET = 'YOUR SECRET FROM PREVIOUS STEPS' 
FIREBASE_URL = 'https://[…].firebaseio.com/' 

(5)該代碼添加到MainHandler(假設你使用的AppEngine):

class MainHandler(webapp2.RequestHandler): 
    def get(self): 
     fb = Firebase(FIREBASE_URL + 'users.json', FIREBASE_SECRET) 

     new_user_key = fb.post({ 
      "job_title": "web developer", 
      "name": "john smith", 
     }) 
     self.response.write(new_user_key) 
     self.response.write('<br />') 

     new_user_key = fb.post({ 
      "job_title": "wizard", 
      "name": "harry potter", 
     }) 
     self.response.write(new_user_key) 
     self.response.write('<br />') 

     fb = Firebase(FIREBASE_URL + 'users/%s.json' % (new_user_key['name'],), FIREBASE_SECRET) 
     fb.patch({ 
      "job_title": "super wizard", 
      "foo": "bar", 
     }) 

     fb = Firebase(FIREBASE_URL + 'users.json', FIREBASE_SECRET) 
     self.response.write(fb.get()) 
     self.response.write('<br />') 

現在,當您導航到您的Firebase實時數據庫時,您應該看到哈利波特作爲用戶和其他人的條目。