• 19-07-2023, 22:10:14
    #1
        def getdata(self, category):
            sayfasayi = False
            dusdata = []
            urunler = []
            x = 1  # Move the initialization outside the loop
            while sayfasayi == False:
                params = {
                    'page': str(x),
                }
                while True:
                    try:
                        response = requests.get("https://www.test.com",     params=params,)
                        if response.status_code == 200:
                            print(x)
                            html = response.json()
                            break
                        else:
                            raise Exception(f"Statu: {response.status_code}")
                for r in html['products']:
                    isim = r['name']
                    url = BASE_URL + r["url"]
                    urunler.append([isim, url])
                try:
                    Burada json işlemi var
                x += 1  # Increment the value of x inside the loop
                if x > int(category["sayfasayisi"]):
                    sayfasayi = True
                    self.urunsayisi += len(urunler)
                    urunler.clear()
                    dusdata.clear()
    Kodum bu şekilde, chatgpt yardım almaya çalıştım fakat çok saçmaladı.
    şimdi kodum burada x=1 olarak başlıyor if x > int(category["sayfasayisi"] olunca tamamlanıyor. if x > int(category["sayfasayisi"] 4 diyelim: 1,2,3,4 olarak istek atıyor. ben 1,2,3,4 aynı anda requests.get isteği atsın istiyorum. Yardımcı olabilir misiniz?
  • 19-07-2023, 22:14:14
    #2
    Aynı anda istek atmak için thread yada async kullanmalısınız
  • 19-07-2023, 22:14:49
    #3
    Ne yapmak istiyorsunuz özetlerseniz kodu okuyup yardımcı olmaya çalışayım.
  • 19-07-2023, 22:18:57
    #4
    kodun güncel hali int(category["sayfasayisi"] sayısında x=1den başlayıp 1,2,3,4,5,6 diye gidiyor. Ben sırayla atmak yerine int(category["sayfasayisi"] sayısında requests.get ile aynı anda tüm istekleri atmak istiyorum. Nasıl yapılacağını maalesef bilmiyorum o kadar iyi değilim ne yazık ki.
  • 19-07-2023, 22:29:11
    #5
    chatgpt derki :

    import requests
    import concurrent.futures
    
    class YourClass:
        def getdata(self, category):
            sayfasayi = False
            dusdata = []
            urunler = []
            x = 1
    
            def process_page(page):
                params = {
                    'page': str(page),
                }
                while True:
                    try:
                        response = requests.get("https://www.test.com", params=params)
                        if response.status_code == 200:
                            print(page)
                            html = response.json()
                            break
                        else:
                            raise Exception(f"Status: {response.status_code}")
                    except Exception as e:
                        print(f"An error occurred: {e}")
    
                for r in html['products']:
                    isim = r['name']
                    url = BASE_URL + r["url"]
                    urunler.append([isim, url])
                try:
                    # Burada json işlemi var
                    pass
                except Exception as e:
                    print(f"An error occurred: {e}")
    
            with concurrent.futures.ThreadPoolExecutor() as executor:
                while sayfasayi == False:
                    futures = [executor.submit(process_page, x)]
                    x += 1
                    if x > int(category["sayfasayisi"]):
                        sayfasayi = True
                        self.urunsayisi += len(urunler)
                        urunler.clear()
                        dusdata.clear()
    concurrent.futures kullanmak için detaylı makale
    https://zetcode.com/python/concurrent-http-requests/
  • 19-07-2023, 22:30:22
    #6
    Bir işlemi bitirmeden diğer işlemi de yapmasını istiyorsanız asenkron fonksiyon olarak yazdırın.
  • 19-07-2023, 22:58:49
    #7
    import requests
    import concurrent.futures
    
    # requests.get isteğini fonksiyon haline getirme
    def send_request(url, params):
        try:
            response = requests.get(url, params=params)
            if response.status_code == 200:
                print(params['page'])  # Sayfanın numarasını yazdırma
                return response.json()
            else:
                raise Exception(f"Statu: {response.status_code}")
        except requests.exceptions.RequestException as e:
            # Handle exception here if needed
            print("Error:", e)
            return None
    
    def getdata(self, category):
        sayfasayi = int(category["sayfasayisi"])
        dusdata = []
        urunler = []
    
        # Eşzamanlı istekler için ThreadPoolExecutor oluşturma
        with concurrent.futures.ThreadPoolExecutor(max_workers=sayfasayi) as executor:
            # İstekleri eşzamanlı olarak gönderme
            futures = {executor.submit(send_request, "https://www.test.com", {'page': str(x)}): x for x in range(1, sayfasayi+1)}
    
            # Tamamlanan istekleri işleme
            for future in concurrent.futures.as_completed(futures):
                x = futures[future]  # Sayfanın numarasını al
                html = future.result()  # İstek sonucunu al
    
                if html:
                    # İşlem yapma ve urunler listesine ekleyerek devam et
                    for r in html['products']:
                        isim = r['name']
                        url = BASE_URL + r["url"]
                        urunler.append([isim, url])
    
        # Burada json işlemi var
    
        self.urunsayisi += len(urunler)
        urunler.clear()
        dusdata.clear()
    Bir deneyin...
  • 20-07-2023, 06:20:19
    #8
    Çok teşekkür ederim, hallettim.