Exemplo n.º 1
0
def get_pets(loc, anm, age, sex, br, am):
    '''
    :param loc: str
    :param anm: str
    :param age: str
    :param sex: str
    :param br: str
    :param am: str
    :return: array

    This function finds the appropriate pets for the user and puts them into the array
    '''
    pf = petpy.Petfinder(give_key())
    available = Array(int(am))
    if loc == '-':
        loc = 'NY'
    if anm == '-':
        anm = None
    if br == '-':
        br = None
    if age == '-':
        age = None
    if sex == '-':
        sex = None
    if am == '-':
        am = 5
    pets_dict = pf.pet_find(loc, anm, br, None, sex, age, count=am)
    if len(pets_dict['petfinder']['header']['status']['message']) != 0:
        return None
    i = 0
    for a in pets_dict['petfinder']['pets']['pet']:
        available[i] = Pet(a['id']['$t'])
        i += 1
    return available
def scheduled_job():

    response = requests.get('https://www.petfinder.com/user/developer-settings/', headers=headers, cookies=cookies)

    soup = BeautifulSoup(response.text, 'html.parser')
    secret_html = soup.find("h3", string="Secret").next_sibling.next_sibling.script.string

    secret = re.findall(r'"(.*?)"', secret_html)[1]

    pf = petpy.Petfinder(key=key, secret=secret)

    animal_list = []

    try:
        animals_all = pf.animals(location = '35.466895,-122.115810', distance=500, pages=None)
    except Exception as x:
        print(x)
    else:
        for animal in animals_all['animals']:
            if animal['contact']['address']['state'] == "CA" and (animal not in animal_list):
                animal_list.append(animal)

        client = pymongo.MongoClient("mongodb+srv://TeamCatViz:RockingTeam#[email protected]/pet_db?retryWrites=true&w=majority")
        client.pet_db.pet_data.delete_many({})
        client.pet_db.pet_data.insert_many(animal_list)
    def __init__(self, pet_id):
        """
        :param pet_id: str

        Initialize pet's id and information about the pet
        """
        self.pet_id = pet_id
        pf = petpy.Petfinder(give_key())
        self.info = pf.pet_get(pet_id)
Exemplo n.º 4
0
def pull_colorado_data(pages, outfile):
    pf = petpy.Petfinder(key=API_KEY, secret=API_SECRET)
    print(f'pulling {pages} page(s) from Petfinder')
    animals = pf.animals(results_per_page=100,
                         pages=pages,
                         return_df=True,
                         location='CO')

    print(f'saving data to {outfile}')
    animals.to_csv(outfile, index=False)
def try_petpy(key):
    pf = petpy.Petfinder(key)
    #get info about cat breeds
    cats = pf.breed_list('cat')
    #get info about available dogs in New York, setting count=1 to see
    #complection of json dictionary
    pets = pf.pet_find('New York', 'cat', count=1)
    #print(pets)
    #get shelters info
    wa_shelter = pf.shelter_list_by_breed('dog', 'Dalamatine')
    return wa_shelter
Exemplo n.º 6
0
 def conectar_APIPetfinder(self, api_key, api_secret):
     """Conecta con la API Petfinder"""
     if (api_key == None or isinstance(api_key, str) == False or
         api_secret == None or isinstance(api_secret, str) == False):
         return "Credenciales no válidas."
     
     self.api_key = api_key
     self.api_secret = api_secret
     """Conectamos con la API Petfinder"""
     try:
         Mascotas.api_petifinder = petpy.Petfinder(self.api_key, self.api_secret)
         return "Conexión realizada correctamente."
     except petpy.exceptions.PetfinderInvalidCredentials:
         return "Credenciales no válidas."
Exemplo n.º 7
0
 def conectarConPetfinder():
     """Obtenemos de las variables de entorno las credenciales para la conexión"""
     api_key = os.environ.get("API_KEY")
     api_secret = os.environ.get("API_SECRET")
     """Comprobamos las credenciales"""
     if (api_key == None or isinstance(api_key, str) == False
             or api_secret == None or isinstance(api_secret, str) == False):
         raise ApiPetfinderConnectionError("Credenciales no válidas.")
     """Conectamos con la API Petfinder."""
     try:
         ConexionAPIPetfinder.__instance = petpy.Petfinder(
             api_key, api_secret)
         return ConexionAPIPetfinder.__instance
     except petpy.exceptions.PetfinderInvalidCredentials:
         raise ApiPetfinderConnectionError("Credenciales no válidas.")
Exemplo n.º 8
0
def random_pet_finder(request):
    #Establish authentication with Petfinder's API using our API key and Secret they provided us and assigning the token to a
    #variable "pf"
    pf = petpy.Petfinder(
        key="cSsIbBmTYRT3LOwOccdgcIoec9iLmZCfqTnWylxDD7R2BLFnwo",
        secret="AxwDvPFnx68TIeKYyT44wcKzxAe4B0nT5XiCV39F")
    #Pull a list of dog breeds from Petfinder's API and refortmat the output from json to a String.
    dog_breeds = str(pf.breeds('dog'))
    #strip json characters from the beginning of the string
    dog_breeds = dog_breeds.strip("{'breeds': {'dog': [")
    #strip json characters from the end of the string
    dog_breeds = dog_breeds.rstrip("]}}")
    #Pull a list of cat breeds from Petfinder's API and refortmat the output from json to a String.
    cat_breeds = str(pf.breeds('cat'))
    #strip json characters from the beginning of the string
    cat_breeds = cat_breeds.strip("{'breeds': {'cat': [")
    #strip json characters from the end of the string
    cat_breeds = cat_breeds.rstrip("]}}")
    context = {'dog_breeds': dog_breeds, 'cat_breeds': cat_breeds}
    return render(request, 'ff_app/random_pet_finder.html', context)
Exemplo n.º 9
0
import petpy
import json
import boto3
from datetime import date

s3 = boto3.resource('s3')

# API
PETFINDER_KEY = [KEY]
PETFINDER_SECRET = [SECRET]

pf = petpy.Petfinder(key=PETFINDER_KEY, secret=PETFINDER_SECRET)
today = date.today()

state_list = ['WA', 'OR', 'CA', 'TX', 'NV']

all_orgs_df = pf.organizations(state=state_list, return_df=True)

corrupted_zips = ['89447', '89429', '89019', '97138']

###### Animal Info ##########
shelter_zipcodes = []
for org in all_orgs_df:
    if all_orgs_df['address.postcode'] not in shelter_zipcodes:
        shelter_zipcodes.append(all_orgs_df['address.postcode'])

# kirkland 98033 zip code is ~3 mile radius
# Did preliminary search for all available pets in both Seattle and Portland and max pages was 22
for zipcode in shelter_zipcodes[0]:
    if zipcode not in corrupted_zips:
        cats_df = pf.animals(animal_type='cat',
Exemplo n.º 10
0
from django.shortcuts import render, reverse, redirect, HttpResponseRedirect
from django.contrib import messages
from .models import User
import bcrypt, petpy
from adopt_app.models import Pet

pf = petpy.Petfinder(key='cET5qlEkj0mMIFKIFkigu7y5mOk6hBeiYKLzylnaHvleQan7y6', secret='gq5c8x0leW4pOs65cXuXu3KV6kiCCPvIxLl4K4sM')


# Create your views here.


def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    elif request.method == "POST":
        if len(request.POST['email']) < 5:
            messages.error(request, "Please enter a valid e-mail", extra_tags="email")
            return redirect(reverse('login'))
        user = User.objects.filter(email__iexact=request.POST['email'])
        request.session['email'] = request.POST['email']
        if user:
            logged_user = user[0]
            if bcrypt.checkpw(request.POST['password'].encode(), logged_user.password.encode()):
                request.session['user_id'] = logged_user.id
                next = request.POST.get('next', '/')
                if next == '':
                    return redirect(reverse('search'))
                return HttpResponseRedirect(next)
            else:
                messages.error(request, "Incorrect password or e-mail", extra_tags="password")
import hidden
import folium
from flask import Flask, render_template
import petpy

key = hidden.give_key()
pf = petpy.Petfinder(key)
data = pf.shelter_get('WA149')
latitude = float(data['petfinder']['shelter']['latitude']['$t'])
longitude = float(data['petfinder']['shelter']['longitude']['$t'])

m = folium.Map()
fg = folium.FeatureGroup(name='shelter_location')
fg.add_child(
    folium.Marker(location=[latitude, longitude],
                  popup='WA shelter',
                  icon=folium.Icon()))
m.add_child(fg)
m.save('templates/map.html')

app = Flask(__name__)


@app.route('/')
def make_map():
    return render_template('map.html')


if __name__ == '__main__':
    app.run(debug=True)
Exemplo n.º 12
0
import petpy
import os
import pandas as pd
import urllib.request
import urllib.error
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool

pf = petpy.Petfinder(key='64kzLueU0iYOqI4RiwILj8gHLm5WiQ5eHdiDgXGmRMrclFiKuy', secret='U5LQhC8hnvKDGsuCg4CIpMcQz1q5ohwtKrUpUPfB')

cat_dog = pf.breeds(types=['cat', 'dog'])