torpyorg / torpy

Pure python Tor client implementation
Apache License 2.0
411 stars 53 forks source link

Not able to use session outside of with-Statement #52

Closed ProtDos closed 8 months ago

ProtDos commented 8 months ago

Hello, my problem is the fact, that I want to use the same session to use in other function of my script. I am working on an app that allows users to send a simple tor request to a given site. I want to use the same session for new requests, generated in the init function. But I always seem to get errors. This is the current code: `import traceback

import requests from kivy import platform from torpy.http.requests import TorRequests from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout import threading from kivy.clock import mainthread import urllib3 if platform == "android": from android.permissions import request_permissions, Permission

class MyApp(App): session = None tor_requests = None

def build(self):
    print("FIND ME HERE")
    print(urllib3.__version__)
    layout = BoxLayout(orientation='vertical')
    layout2 = BoxLayout(orientation='horizontal')

    self.label = Label(text="Press the button to get IP address")

    button = Button(text="Get IP Address")
    button.bind(on_press=self.get_ip_threaded)
    layout2.add_widget(button)

    button = Button(text="Test Session")
    button.bind(on_press=self.test_thing_threaded)
    layout2.add_widget(button)

    layout.add_widget(self.label)
    layout.add_widget(layout2)

    return layout

def test_session(self, *_):
    if self.session is None:
        print("No session exists yet.")
        return
    else:
        print("Session exists. Sending a test request.")
        try:
            print(self.session)
            # with self.tor_requests as r:
            #     with r.get_session() as s:
            #         print(s)
            #         response = s.get("http://httpbin.org/ip").json()
            response = self.session.get("http://httpbin.org/ip").json()
            print(response)
            ip_address = response["origin"]
            self.update_label(f"Your IP address is: {ip_address}")
        except Exception as e:
            traceback.format_exc()
            print(e)
            self.update_label(f"Error: {e}")

def get_ip_threaded(self, _):
    thread = threading.Thread(target=self.get_ip)
    thread.start()

def test_thing_threaded(self, _):
    thread = threading.Thread(target=self.test_session)
    thread.start()

def get_ip(self, *_):
    try:
        if platform == "android":
            request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.MANAGE_EXTERNAL_STORAGE])
        self.update_label(f"Loading...")

        with TorRequests() as self.tor_requests:
            print(self.tor_requests)
            print("building circuit...")
            with self.tor_requests.get_session() as self.session:
                response = self.session.get("http://httpbin.org/ip").json()
                # response2 = self.session.get("http://httpbin.org/ip").json()

        print(response)
        # print(response2)
        ip_address = response["origin"]

        self.update_label(f"Your IP address is: {ip_address}")
    except Exception as e:
        traceback.format_exc()
        print(e)
        self.update_label(f"Error: {e}")

@mainthread
def update_label(self, text):
    self.label.text = text

if name == 'main': MyApp().run() `

I tried using this in test_session(), but it simply created a new session. with self.tor_requests as r: with r.get_session() as s: print(s) response = s.get("http://httpbin.org/ip").json()

How can I fix it? Or are there better ways to do it?

ProtDos commented 8 months ago
from torpy.http.requests import TorRequests

# This doesn't work
req = TorRequests()
sess = req.get_session()

r = sess.get("http://example.org")
print(r.text)

exit()

""" # This works
with TorRequests() as tor_requests:
    print(tor_requests)
    print("building circuit...")
    with tor_requests.get_session() as session:
        response = session.get("http://httpbin.org/ip").json()

print(response)
ip_address = response["origin"]

print(f"Your IP address is: {ip_address}")
"""

The code above is what I have tried (using it without with), but it raised this error:

Traceback (most recent call last):
  File "D:\...\...\v2.py", line 6, in <module>
    r = sess.get("http://example.org")
AttributeError: '_GeneratorContextManager' object has no attribute 'get'
ProtDos commented 8 months ago

Fixed by:

`from requests import Session from torpy.http.adapter import TorHttpAdapter from torpy.http.requests import TorRequests

req = TorRequests() req.enter()

adapter = TorHttpAdapter(req._guard, req._hops_count, retries=0) s = Session() s.headers.update(req._headers) s.mount('http://', adapter) s.mount('https://', adapter)

r = s.get("http://httpbin.org/ip") print(r.text)`