1

I'm making android app with django server.

I use django rest framework

When android app send some data to server, there is no log django server showing in cmd. and server do not get any request.

But with postman, everything works well

I think there is an error at server part

This is my django settings.py

import os
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


SECRET_KEY = '8wxm7e451m83j%)c8a+cf+#&#vg-qr1l-l%jx+ri@#r2^3_%nw'

DEBUG = True

ALLOWED_HOSTS = ['*', '.pythonanywhere.com']



INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'corsheaders',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    'diary',
]

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'diary.backend.MyTokenAuthentication',
    ),
    'AUTHENTICATION_BACKENDS' : (
        'diary.backend.MyBackend',
    )

}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_URL = '/image/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')

STATIC_URL = '/static/'
CORS_ALLOW_CREDENTIALS = True
ACCOUNT_EMAIL_REQUIRED = False
#REST_USE_JWT = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGINS_WHITELIST = (
    'localhost:1245',
    '127.0.0.1:1245',
)

Could you tell me what part should i fix or is it android's problem

Edit

I put some android code. I use retrofit2, rxJava2 and Koin as di

this is function in my viewModel

fun verifyToken(token: String) = addDisposable(userService.verifyToken(TokenRequest(token)), getMsgObserver())

This is addDisposable function

fun addDisposable(disposable: Single<*>, observer: DisposableSingleObserver<Any>) {
        compositeDisposable.add(
            disposable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribeWith(observer)
        )
}

This is all about getMsgObserver

fun getMsgObserver() = MsgDisposableSingleObserver()

inner class MsgDisposableSingleObserver : DisposableSingleObserver<Any>() {

    override fun onSuccess(t: Any) = filterMsgFromResponse(t)

    override fun onError(e: Throwable) {
        networkError.call()
}

And this is UserService interface and it's impl

interface UserService {
    fun verifyToken(tokenRequest: TokenRequest) : Single<retrofit2.Response<Response<Any>>>
}

class UserServiceImpl(private val api: UserApi) : UserService {
    override fun verifyToken(tokenRequest: TokenRequest) = api.verifyToken(tokenRequest)
}

And this is UserApi which used by UserServiceImpl

interface UserApi {
    @POST("/diary/verify/")
    fun verifyToken(@Body token: TokenRequest) : Single<retrofit2.Response<Response<Any>>>
}

when i call function verifyToken i get an error through MsgDisposableSingleObserver's onError function and Error Message is

failed to connect to /10.80.162.133 (port 1289) from /10.80.163.129 (port 60989) after 10000ms

Edit

val retrofit: Retrofit = Retrofit
    .Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

The BASE_URL is server url which i try to connect to

HyeonSeok
  • 589
  • 1
  • 5
  • 18
  • I think the problem not from your Django settings, double check you network config and make sure you can ping from your phone device to your server – Phan Dinh Dec 17 '19 at 08:43
  • @PhanDinh I test with my phone and other laptop, but server didn't get any request and clients didn't get any response, it is only timeout error client got. Is there any solution to solve it? – HyeonSeok Dec 17 '19 at 09:05
  • Try exposing port 1289 on your server and make sure they are on the same network. https://www.cyberciti.biz/faq/linux-unix-open-ports/ – Phan Dinh Dec 17 '19 at 10:09
  • It sounds like the problem is in the Android code, not on the server side. Perhaps you could post the Android code you're using? – Giles Thomas Dec 17 '19 at 19:13
  • 1
    Does the Android code have any place where you specify the URL to the server that you're trying to connect to? I don't see anything like that in the code you added. – Giles Thomas Dec 18 '19 at 12:42
  • @GilesThomas I added server url – HyeonSeok Dec 18 '19 at 23:27
  • I don't think you're using the same network. Your Android phone IP address is `10.80.163.129` whereas the server's `10.80.162.133`. Notice the difference `163` and `162`. And also make sure that your server's Firewall is **Turned Off** for testing purposes. In Postman it works because you might be using `localhost` instead of the IP address of the Django server. If this is not the case, then tell us the value of `BASE_URL` variable in your code. – Shashanth Dec 19 '19 at 05:17
  • Refer to this StackOverflow [thread](https://stackoverflow.com/q/22144189/5180017) – Shashanth Dec 19 '19 at 05:20
  • I solved this problem by creating new django project. My BASE_URL is "http://10.80.162.133:8080". My server and phone use same network but I'm using school network which blocks foreign address's access. does it can be problem? but everything works well with other project using this network – HyeonSeok Dec 19 '19 at 06:19

0 Answers0